Windows Batch Scripting

Must Watch!



MustWatch
batchTips


Batch Script Tutorial

https://tutorialreference.com/batch-scripting/batch-script-tutorial A Batch Script is text file containing lines with commands that get executed in sequence by the Microsoft command interpreter (cmd.exe).

 What is a Batch Script?

A Batch Script is text file containing lines with commands that get executed in sequence by the Microsoft command interpreter (cmd.exe). Batch scripts are stored in text files containing lines with commands that get executed in sequence, one after the other. Batch scripts files have the special extension BAT (.bat) or CMD (.cmd). This type of file is recognized by the Operating System and executed through an interface (called shell) provided by a system file called the command interpreter. Note: Running a batch file is a simple matter of just clicking on it. Batch files can also be run in a command prompt or the Start-Run line. In this case, the full path must be used, unless the file is in the path environment.

 Features and Uses of Batch Script

Some of the features of Batch Script: It can read user input so that it can process it further. It has control structures such as for, if, while, switch for better automation and scripting. It supports advanced features such as Functions and Arrays. It supports regular expressions. It can include other programming codes. Some of the common uses of Batch Script are: Setting up servers for different purposes. Automating housekeeping activities such as deleting unwanted files or log files. Automating the deployment of applications from one environment to another. Installing programs on various machines at once.

 What is the Windows command interpreter?

The command interpreter is a file responsible for handling and processing the command done at the MS-DOS or Windows command line interface. The command interpreter for Windows is cmd.exe. This application is responsible for creating the command window, accepting configuration commands, and accessing built-in commands such as the Dir command. Note: For Windows scripting, cmd.exe is a legacy technology; a modern equivalent is PowerShell, which is based on .NET. PowerShell's capabilities vastly outstrip those of cmd.exe

Interpretation of a Command line

Parsing a command line into a sequence of commands is complex. There are four main things to consider: Variable substitution: A command line is scanned for variable specifications, and any found are replaced with the contents of those variables. Quoting: Special characters can be quoted, to remove their special meanings. Syntax: Command lines are developed into a sequence of commands according to a syntax. Redirection: Redirection specifications are applied, and removed from the command line, before an individual command in a sequence is executed.

Batch Script Environment

Let's see the environment related to Batch Script.

 Writing and Executing

The easiest way to create a batch file is to use Notepad (but you can use any other text editor). This is the simplest tool for creation of batch files. The execution environment for the batch scripts is the command prompt, or cmd.exe, on WWindows systems. You can launch cmd.exe in different ways: Via the run command or search bar in Start menu (easiest way) Double-click on the cmd file in C:\Windows\System32 Once cmd.exe is launched, the command prompt will be displayed.

 Environment Variables

In order to run batch files from the command prompt, you either need to go to the location to where the batch file is stored or alternatively you can enter the file location in the path environment variable. Thus assuming that the batch file is stored in the location C:\Application\bin, you would need to follow these instructions for the PATH variable inclusion. In Windows, you need to append the String C:\Application\bin to the end of the system variable PATH.

Batch Script Frequently Used Commands

The following table shows some of the frequently used batch commands:
CommmandDescription
VERThis batch command shows the version of MS-DOS you are using.
ASSOCThis is a batch command that associates an extension with a file type (FTYPE), displays existing associations, or deletes an association.
CDThis batch command helps in making changes to a different directory, or displays the current directory.
CLSThis batch command clears the screen.
COPYThis batch command is used for copying files from one location to the other.
DELThis batch command deletes files and not directories.
DIRThis batch command lists the contents of a directory.
DATEThis batch command help to find the system date.
ECHOThis batch command displays messages, or turns command echoing on or off.
EXITThis batch command exits the DOS console.
MDThis batch command creates a new directory in the current location.
MOVEThis batch command moves files or directories between directories.
PATHThis batch command displays or sets the path variable.
PAUSEThis batch command prompts the user and waits for a line of input to be entered.
PROMPTThis batch command can be used to change or reset the cmd.exe prompt.
RDThis batch command removes directories, but the directories need to be empty before they can be removed.
RENRenames files and directories.
REMThis batch command is used for remarks in batch files, preventing the content of the remark from being executed.
STARTThis batch command starts a program in new window, or opens a document.
TIMEThis batch command sets or displays the time.
TYPEThis batch command prints the content of a file or files to the output.
VOLThis batch command displays the volume labels.
ATTRIBDisplays or sets the attributes of the files in the current directory.
CHKDSKThis batch command checks the disk for any problems.
CHOICEThis batch command provides a list of options to the user.
CMDThis batch command invokes another instance of command prompt.
COMPThis batch command compares 2 files based on the file size.
CONVERTThis batch command converts a volume from FAT16 or FAT32 file system to NTFS file system.
DRIVERQUERYThis batch command shows all installed device drivers and their properties.
EXPANDThis batch command extracts files from compressed .cab cabinet files.
FINDThis batch command searches for a string in files or input, outputting matching lines.
FORMATThis batch command formats a disk to use Windows-supported file system such as FAT, FAT32 or NTFS, thereby overwriting the previous content of the disk.
HELPThis batch command shows the list of Windows-supplied commands.
IPCONFIGThis batch command displays Windows IP Configuration. Shows configuration by connection and the name of that connection.
LABELThis batch command adds, sets or removes a disk label.
MOREThis batch command displays the contents of a file or files, one screen at a time.
NETProvides various network services, depending on the command used.
PINGThis batch command sends ICMP/IP "echo" packets over the network to the designated address.
SHUTDOWNThis batch command shuts down a computer, or logs off the current user.
SORTThis batch command takes the input from a source file and sorts its contents alphabetically, from A to Z or Z to A. It prints the output on the console.
SUBSTThis batch command assigns a drive letter to a local folder, displays current assignments, or removes an assignment.
SYSTEMINFOThis batch command shows configuration of a computer and its operating system.
TASKKILLThis batch command ends one or more tasks.
TASKLISTThis batch command lists tasks, including task name and process id (PID).
XCOPYThis batch command copies files and directories in a more advanced way.
TREEThis batch command displays a tree of all subdirectories of the current directory to any level of recursion or depth.
FCThis batch command lists the actual differences between two files.
DISKPARTThis batch command shows and configures the properties of disk partitions.
TITLEThis batch command sets the title displayed in the console window.
SETDisplays the list of environment variables on the current system.

Batch Script Files

Let's see how to create, save, execute, and edit batch files. In addition, DOs and DON'Ts suggestions are given.

 Creating and Saving Batch Files

The easiest way to create a batch file is to use Notepad, but you can use any other text editor. For example, let's try to create a basic batch file following these steps using Windows Notepad: Open Start. Search for Notepad and click the top result to open the text editor. Type the following lines in the text file to create a batch file: @ECHO OFF ECHO Hello World! PAUSE The above script outputs the phrase, "Hello World! " on the screen. @ECHO OFF Shows the message on a clean line disabling the display prompt. Usually, this line goes at the beginning of the file. (You can use the command without the @ symbol, but it's recommended to include it to show a cleaner return.) ECHO prints the text after the space on the screen. PAUSE allows the window to stay open after the command has been executed. Otherwise, the window will close automatically as soon as the script finishes executing. Click the File menu, select the Save as option and confirm a name for the script (for example "first-script.bat") Note:You can use PAUSE command at the end of the script or after a specific command when running multiple tasks and want to pause between each line. Note: Some general rules to keep in mind when naming batch files Try to avoid spaces when naming batch files, because they sometimes create problems when called by other scripts. Don't name them after common batch files available in the system, such as ping.cmd.

 Executing Batch Files

Once the batch file is created, simply double-click to run it. Note: There are several ways to run a batch file: on-demand using the command prompt or the file explorer; on startup by defining a configuration to be performed at each startup; with Task Scheduler to automatically run the batch file at a specific time.

 Modifying Batch Files

The easiest way to edit a batch file is to use Notepad, but you can use any other text editor. Simply open the batch file with Notepad (or any other text editor), make the changes, and save.

 Best Practice Suggestions

Note:Programming best practices should always be followed when writing code, regardless of the programming language used.

DOs

Documenting code with comments (see Batch Script Comments Chapter to learn more) Validating input Check variables before using them being sure that they are initialized. Indentation

DON'Ts

Avoid one-line code (i.e. multiple command lines joined into a single line by ANDs and ORs) and use a block of code. Avoid nested block codes (nested if-else) and use subroutines instead. Don't use variable names as command names

Batch Script Syntax

 Batch Script Syntax

Turn off echo

Usually, the first line of a batch file consists of: @echo off The command echo off turns off the display for the whole script, except for the "echo off" command itself. The @ sign in front makes the command apply to itself as well. Note:By default, a batch file will display its command as it runs. The purpose of this first command is to turn off this display.

Documentation

Very often batch files also contains lines that start with the Rem command. This is a way to enter comments and documentation. Rem This is a documentation line Note: The computer ignores everything on the same line after Rem. For batch files of increasing complexity, it is often a good idea to have comments.

 First Batch Script Program

Open Notepad and enter the following example: FirstExample.bat @echo off Rem List and save to file all the files in the directory Program files dir "C:\Program Files" > C:\lists.txt echo "The program has completed" The code does the following: Uses the echo off command to ensure that the commands are not shown when the code is executed. The Rem command is used to add a comment to say what exactly this batch file does. The dir command is used to take the contents of the location C:\Program Files. The > command is used to redirect the output to the file C:\lists.txt. Finally, the echo command is used to tell the user that the operation is completed.

Batch Script Variables

 Types of Variables

There are two types of variables in batch files. One is for parameters that can be passed when the batch file is called, and the other is done through the set command.

Command Line Arguments

Batch scripts support the concept of command-line arguments, in which arguments can be passed to the batch file when it is invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on. For example, the batch script below accepts 3 command line arguments and echo's them to the command line screen: parameter-test.bat @echo off echo %1 echo %2 echo %3 If the above batch script is stored in a file called parameter-test.bat and we were to run the batch as: C:\my\path>parameter-test.bat 1 2 3 And the above command produces the following output: 1 2 3 Note: If more parameters are passed than are used, the extra ones will be ignored. For example, here the fourth parameter is ignored but the output remains the same as above: C:\my\path>parameter-test.bat 1 2 3 4

set Command

The other way to initialize variables is the set command. The syntax of the set command is as follows. set /A variable_name=value where: variable_name is the name of the variable you want to set. value is the value which needs to be set against the variable. /A is used if the value needs to be numeric. For example, in this script a variable called message is defined and set with the value of "Hello World". set-example.bat @echo off set message=Hello World echo %message% Note:To display the value of the variable, the variable needs to be enclosed in the % sign. And the above command produces the following output: Hello World

 Numeric Variables

It is possible to define a variable to hold a numeric value. This can be done by using the /A switch (also known as flag). For example: numeric-example.bat @echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c% where: we assign the values 5 and 10 to two variables a and b respectively. we sum these values and store the result in the variable c. Finally, we display the value of the variable c. The output of the above script is 15.

Arithmetic Operators

All the arithmetic operators work in batch files. For example: arithmetic-example.bat @echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c% SET /A c = %a% - %b% echo %c% SET /A c = %b% / %a% echo %c% SET /A c = %b% * %a% echo %c% And the output is: 15 -5 2 50 Note:You can learn more about operators in our Batch Script Operators Chapter

 Local and Global Variables

In Batch Scripting there are variables with local and global scope. By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of the script. After calling SETLOCAL, any variable assignment is cancelled when ENDLOCAL, EXIT or when execution reaches the end of file (EOF) in the script is called. The difference between setting local and global variables is shown in the following script: @echo off set globalvar = 5 SETLOCAL set var = 13145 set /A var = %var% + 5 echo %var% echo %globalvar% ENDLOCAL Note: The globalvar is defined with a global scope and it is available throughout the entire script. The variable var is defined in a local scope because it is enclosed between a SETLOCAL and ENDLOCAL block. Therefore, this variable will be destroyed as soon as the ENDLOCAL instruction is executed.

 Environment Variables

Environment Variables are preferable when there are variables that would be used across batch files. Note:Once the environment variable is defined, it can be accessed via the % sign (like any variable). The following example shows how to see the JAVA_HOME defined on a system. @echo off echo %JAVA_HOME% C:\mypath\JAVA5.0\jre Note:The JAVA_HOME variable is a key component that is normally used by a wide variety of Java-based applications.

Batch Script Comments

 Batch Script Comments

Comments in Batch Script can be made in two ways: using the Rem statement using the :: statement Note: It's always a good practice to add comments. This is useful for script maintenance, to understand what the script actually does.

Comments Using the Rem Statement

Comments in Batch Script can be made using the Rem command. Any text which follows the Rem statement will be treated as comments and will not be executed. Rem Example Rem My comment where My comment is the comment that needs to be added. For example, in the following snippet, the Rem command is used to describe what the program does. Notice that the line with the Rem statement will not be executed. HelloWorld.bat @echo off Rem This program displays Hello World set message=Hello World echo %message% Hello World

Comments Using the :: Statement

The other way to create comments in Batch Script is via the :: command. Any text which follows the :: statement will be treated as comments and will not be executed. :: Example :: My comment where My comment is the comment that needs to be added. Like the Rem command, the :: command is used to describe what the program does. HelloWorld.bat @echo off :: This program displays Hello World set message=Hello World echo %message% Hello World Note:If you have too many lines of Rem, it could slow down the code, because in the end each line of code in the batch file still needs to be executed.

Batch Script String Manipulation

In Batch Script, a string is an ordered collection of characters. Batch scripts have the following commands which are used to carry out string manipulation in strings: %variable:~num_chars_to_skip% %variable:~num_chars_to_skip,num_chars_to_keep% and this can include negative numbers: %variable:~num_chars_to_skip, -num_chars_to_keep% %variable:~-num_chars_to_skip,num_chars_to_keep% %variable:~-num_chars_to_skip,-num_chars_to_keep% Note:The above commands will be useful for some manipulations explained below (e.g., for substrings). The most common operations on strings in Batch Scripting are explained below:

Create a String

A string can be created using the set command in the following way: Example of String creation @echo off :: This program displays Hello World set message=Hello World echo %message% Hello World

Empty String

An empty string can be created by assigning no value to it during initialization: Empty string initialization set variable_name= To check for an empty string, you need to enclose the variable name in square brackets and compare it with a value in square brackets: Empty String Check if [%variable_name%]==[] echo "True" Below is a complete example with empty strings: Example of Empty String @echo off set a= set b=Hello if [%a%]==[] echo "String A is empty" if [%b%]==[] echo "String B is empty " String A is empty

String Interpolation

String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. In Batch Scripting, the string interpolation can be done using the set command and lining up the numeric defined variables or any other literals in one line when using the set command. Example of String Interpolation @echo off set a=Hello set b=World set /A d=123 set c=%a% and %b% %d% echo %c% Hello and World 123

String Concatenation

You can use the set operator to concatenate two strings or a string and a character, or two characters Example of String Concatenation @echo off SET a=Hello SET b=World SET c=The %a% and the %b% echo %c% The Hello and the World

String Length

In Batch Scripting there is no length function defined to find the length of a string. But there are custom-defined functions which can be used for the same. For example, you can reuse what is defined below: Example of String Length @echo off set str=Hello World call :strLen str strlen echo String is %strlen% characters long exit /b :strLen setlocal enabledelayedexpansion :strLen_Loop if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop (endlocal & set %2=%len%) goto :eof 11 Note: Some points about the example above: The actual code which finds the length of string is defined in the :strLen block. The length of the string is maintained in the variable len.

String to Integer

A variable that has been set as a string using the set variable can be converted to an integer using the /A flag using the set variable. Example of String to Integer @echo off set var=12345 set /A var=%var% + 5 echo %var% 12350

Align Right

It is used to align text to the right, normally to improve readability of columns of numbers. In the following example we add leading spaces to a string to make sure the output lines up: we want for variables no longer than 8 characters to add 8 spaces at the beginning and then show only the last 8 characters of the variable. Example of Align Right @echo off set x=3000 set y=2 set x=%x% set y=%y% echo.X=%x:~-8% echo.Y=%y:~-8% X= 3000 Y= 2 Note:Note that the value 2 is aligned with the unit columns when displaying the numbers. Note:The echo. command is used to write a blank line on the screen.

Substring starting at the beginning of the string (Left string)

This is used to extract characters from the beginning of a string. The substring syntax is as follows: set substring=%variable_name:~from_index,to_index% Note:To extract characters from the beginning of a string you need to use zero as first index, i.e. %variable_name:~0,to_index% An example: Example of Left String set str=Helloworld echo.%str% set str=%str:~0,5% echo.%str% Helloworld Hello

Substring (Mid string)

This is used to extract a substring via the position of the characters in the string. The substring syntax is as follows: set substring=%variable_name:~from_index,to_index% Example of Mid String @echo off set str=Helloworld echo %str% set str=%str:~3,7% echo %str% Helloworld loworld

Substring starting at the end of the string (Right string)

This is used to extract characters from the end of a string. The substring syntax is as follows: set substring=%variable_name:~-index% Note:To extract characters from the end of a string, it is necessary to use - followed by the number of characters to be extracted, i.e. %variable_name:~-index%. Example of Right String @echo off set str = This message needs changed. echo %str% set str = %str:~-8% echo %str% This message needs changed. changed.

Remove

The string substitution feature can also be used to remove a substring from another string. The syntax is as follows: set newstr=%variable_name:stringtobereplaced=newstring% Note:To remove a substring, you must leave the newstring parameter in %variable_name:stringtobereplaced=newstring% empty. An example: Example of Remove @echo off set str=Batch scripts is easy. It is really easy. echo %str% set str=%str:is =% echo %str% Batch scripts is easy. It is really easy. Batch scripts easy. It really easy.

Remove Both Ends

This is used to remove the first and the last character of a string. The syntax is as follows: set substring=%variable_name:~from_index,to_index% Note:To remove both ends from a string, it is necessary to substring from the second character to the second-to-last, i.e. %variable_name:~1,-1%. An example: Example of Remove Both Ends @echo off set str=Batch scripts is easy. It is really easy echo %str% set str=%str:~1,-1% echo %str% Batch scripts is easy. It is really easy atch scripts is easy. It is really eas

Remove All Spaces

This is used to remove all spaces in a string by substitution. The syntax is as follows: set substring=%variable_name: =% An example: Example of Remove All Spaces @echo off set str=This string has a lot of spaces echo %str% set str=%str: =% echo %str% This string has a lot of spaces Thisstringhasalotofspaces

Replace a String

To replace a substring with another string use the string substitution feature. The syntax is as follows: set newstr=%variable_name:stringtobereplaced=newstring% Note:To replace a substring, you must define the values of the stringtobereplaced and newstring parameters in %variable_name:stringtobereplaced=newstring%. Example of Replace a String @echo off set str=This message needs changed. echo %str% set str=%str:needs=has% echo %str% This message needs changed. This message has changed.

Batch Script Arrays

Arrays do not exist as a type in Batch Script, but it can be implemented using the set command ad a for loop: Each element of the array needs to be defined with the set command. The for loop would be required to iterate through the values of the array.

Creating an Array

You can create an array using the following set command: set a[0]=1 where 0 is the index of the array and 1 is the value assigned to the first element of the array. Note:This requires defining each element of the array using the set command. Another way to implement arrays is to define a list of values and iterate through the list of values: @echo off set list=1 2 3 4 (for %%a in (%list%) do ( echo %%a )) 1 2 3 4

Accessing Arrays

You can retrieve a value from the array by passing the index of the value you want to retrieve in square brackets immediately after the name of the array. AccessingExample.bat @echo off set a[0]=1 echo %a[0]% 1 Consider the following more complex example: ComplexAccessingExample.bat @echo off set a[0]=1 set a[1]=2 set a[2]=3 echo The first element of the array is %a[0]% echo The second element of the array is %a[1]% echo The third element of the array is %a[2]% The first element of the array is 1 The second element of the array is 2 The third element of the array is 3

Modifying an Array

To add an element to the end of the array, you can use the set command along with the last index of the array element: AddLastElement.bat @echo off set a[0]=1 set a[1]=2 set a[2]=3 Rem Adding an element at the end of an array Set a[3]=4 echo The last element of the array is %a[3]% The last element of the array is 4 You can modify an existing element of an Array by assigning a new value at a given index using the set command: ModifyLastElement.bat @echo off set a[0]=1 set a[1]=2 set a[2]=3 Rem Setting the new value for the second element of the array Set a[1]=5 echo The new value of the second element of the array is %a[1]% The new value of the second element of the array is 5

Iterating Over an Array

Iteration of an array is achieved by using the for loop and reviewing each element of the array. An example of how to implement iteration on an array: Iteration.bat @echo off setlocal enabledelayedexpansion set fruit[0]=banana set fruit[1]=apple set fruit[2]=pear set fruit[3]=orange set fruit[4]=peach set fruit[5]=watermelon for /l %%n in (0,1,5) do ( echo !fruit[%%n]! ) Note: Each element of the array needs to be specifically defined using the set command. The for loop with the /l parameter for moving through ranges is used to iterate through the array. The above script produces the following output: banana apple pear orange peach watermelon

Length of an Array

The length of an array is done by iterating over the list of values in the array since there is no direct function to determine the number of elements in an array. LengthOfArray.bat @echo off set Arr[0]=1 set Arr[1]=2 set Arr[2]=3 set Arr[3]=4 set "x=0" :SymLoop if defined Arr[%x%] ( call echo %%Arr[%x%]%% set /a "x+=1" GOTO :SymLoop ) echo "The length of the array is" %x% 1 2 3 4 "The length of the array is" 4

Creating Structures in Arrays

Structures can also be implemented in batch files, using a little extra code for implementation. StructureExample.bat @echo off set obj[0].Name=Tom set obj[0].ID=1 set obj[1].Name=Ryan set obj[1].ID=2 set obj[2].Name=John set obj[2].ID=3 FOR /L %%i IN (0 1 2) DO ( call echo Name = %%obj[%%i].Name%% call echo Value = %%obj[%%i].ID%% ) Note: Each variable defined using the set command has 2 values associated with each index of the array. The variable i is set to 0 so that we can loop through the structure will the length of the array which is 3. We always check for the condition on whether the value of i is equal to the value of len and if not, we loop through the code. We are able to access each element of the structure using the obj[%i%] notation. The above script produces the following output: Name = Tom Value = 1 Name = Ryan Value = 2 Name = John Value = 3

Batch Script Conditional Branching

 Conditional Branching

Batch Script Conditional Branching is made using the if and if-else statements. The programmer must specify one or more conditions to be evaluated or tested by the program, along with one or more instructions to be executed if the condition is true and, optionally, other instructions to be executed if the condition is false. Note:Note that the evaluation of the condition is "case-sensitive."

if Statement

The general working of if statement is that first a condition is evaluated in the if statement. If the condition is true, it then executes the statements. if Syntax if(condition) do_something The following is an example of how if statements can be used: @echo off set /A a=5 set /A b=10 set /A c=%a% + %b% if %c%==15 echo "The value of variable c is 15" if %c%==10 echo "The value of variable c is 10" "The value of variable c is 15"

if-else Statement

The general operation of the if-else statement is that first a condition in the if statement is evaluated. If the condition is true, the next instruction is executed and it stops before the else condition, exiting the loop. If the condition is false, it executes the instructions in the else instruction block and then exits the loop. if-else Syntax if (condition) (do_something) else (do_something_else) The following is an example of how if-else statements can be used: @echo off set /A a=5 set /A b=10 set /A c=%a% + %b% if %c%==15 (echo "The value of variable c is 15") else (echo "Unknown value") if %c%==10 (echo "The value of variable c is 10") else (echo "Unknown value") "The value of variable c is 15" "Unknown value" Note:Each if-else instruction is placed between () parentheses. If the parentheses are not placed to separate the code of the if-else , the instructions will not be valid as if-else instructions.

Nested if Statement

Sometimes, there is a requirement to have multiple if statement embedded inside each other, for example: Nested if Syntax if(condition1) if (condition2) do_something In this example, only if condition1 and condition2 are met, will the code in the do_something block be executed. The following is an example of how nested if statements can be used: @echo off SET /A a = 5 SET /A b = 10 if %a%==5 if %b%==10 echo "The value of the variables is correct" "The value of the variables is correct"

 Checking Variables

The common use of conditional branching in Batch Script is the checking of variables set in Batch Script itself. The evaluation can be done for both strings and numbers.

Checking Integer Variables

@echo off set /A a=5 set /A b=10 set /A c=%a% + %b% if %c%==15 echo "The value of variable c is 15" if %c%==10 echo "The value of variable c is 10" if %c%==15 (echo "The value of variable c is 15") else (echo "Unknown value") if %c%==10 (echo "The value of variable c is 10") else (echo "Unknown value") "The value of variable c is 15" "The value of variable c is 15" "Unknown value"

Checking String Variables

@echo off set str1=String1 set str2=String2 if %str1%==String1 echo "The value of variable String1" if %str2%==String3 echo "The value of variable c is String3" if %str1%==String1 (echo "The value of variable String1") else (echo "Unknown value") if %str2%==String3 (echo "The value of variable c is String3") else (echo "Unknown value") "The value of variable String1" "The value of variable String1" "Unknown value" Note:Note that the evaluation of the condition is "case-sensitive."

Checking Command Line Arguments

@echo off echo %1 echo %2 echo %3 if %1%==1 echo "The value is 1" if %2%==2 echo "The value is 2" if %3%==3 echo "The value is 3" if %1%==1 (echo "The value is 1") else (echo "Unknown value") if %2%==2 (echo "The value is 2") else (echo "Unknown value") if %3%==3 (echo "The value is 3") else (echo "Unknown value") The output of the above snippet is below (arguments are 1 2 3) 1 2 3 "The value is 1" "The value is 2" "The value is 3" "The value is 1" "The value is 2" "The value is 3"

 Special Cases

if defined

A special case of the if statement is the if defined statement, which is used to verify the existence of a variable. if defined somevariable somecommand An example of how the if defined statement can be used: @echo off set str1=String1 set str2=String2 if defined str1 echo "Variable str1 is defined" if defined str3 (echo "Variable str3 is defined") else (echo "Variable str3 is not defined") "Variable str1 is defined" "Variable str3 is not defined"

if exists

Another special case of the if instruction is the if exists instruction, used to verify the existence of a file. if exist somefile.extension do_something An example of how the if exists statement can be used: @echo off if exist C:\path\myfile.txt echo "File exists" if exist C:\path\myfile2.txt (echo "File exists") else (echo "File does not exist") "File exists" "File does not exist"

if errorlevel

Another special case is if errorlevel, used to check the output codes of the last command executed. Note: Several commands issue integer output codes to indicate the status of the command. Generally, commands change to 0 if the command was successfully completed and to 1 if the command failed. The general syntax of this statement is below: if errorlevel n somecommand where n is one of the integer exit codes.

goto Statement

The goto command allows you to go to a particular section of code. The target section is labeled with a line at the beginning that has a name with a leading colon. Note:Typically, the execution of a batch file proceeds line by line, and the commands in each line are executed in turn. For example: ... goto :label ...some commands :label ...some other commands A label can be a line anywhere in the script, including before the goto command. Note:goto commands often occur in if statements. if (condition) goto :label A more complex example of how the goto instruction works is shown below: @echo off set /A a=5 if %a%==5 goto :labela if %a%==10 goto :labelb :labela echo "The value of a is 5" exit /b 0 :labelb echo "The value of a is 10" "The value of a is 5"

Batch Script Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations on certain values. The following types of operators are possible in Batch Scripts: Unary Operators Arithmetic operators Relational operators Logical operators Assignment operators Bitwise operators Redirection operators Other operators

Batch Script Date and Time

The date and time in Batch Scripting have the following two basic commands for retrieving the date and time of the system.

date command

The date command gets the system date. Example @echo off echo %date% 07/20/2022 Note:The output is different depending on the localization of the operating system.

time command

The time command sets or displays the time. Example @echo off echo %time% 18:15:44.79

Extract current day/month/year in a locale-independent way

The following batch code returns the components of the current date in a locale-independent way and stores day, month and year in the variables CurrDay, CurrMonth and CurrYear, respectively: @echo off for /F "skip=1 delims=" %%F in (' wmic PATH Win32_LocalTime GET Day^,Month^,Year /FORMAT:TABLE ') do ( for /F "tokens=1-3" %%L in ("%%F") do ( set CurrDay=0%%L set CurrMonth=0%%M set CurrYear=%%N ) ) set CurrDay=%CurrDay:~-2% set CurrMonth=%CurrMonth:~-2% echo Current day : %CurrDay% echo Current month: %CurrMonth% echo Current year :%CurrYear% Current day : 20 Current month: 07 Current year :2022

Batch Script Input and Output

There are three universal "files" for keyboard input, screen text printing, and screen error printing. The Standard Input file, known as stdin, contains the input to the program/script. The Standard Output file, known as stdout, is used to write the output to be displayed on the screen. The Standard Error file, known as stderr, contains all the error messages to be displayed on the screen. Each of these three standard files, otherwise known as the standard streams, are referenced using numbers: stdin is file 0 stdout is file 1 stderr is file 2

Redirecting Output

A common practice in batch scripting is to send the output of a program to a log file. You use the > operator to send, or redirect, stdout or stderr to another file. The following example shows how this can be done. In the following example, the stdout of the command dir C:\ is redirected to the file list.txt. dir C:\ > list.txt If you append the number 2 to the redirection filter, then it would redirect the stderr to the file lists.txt. dir C:\ 2> list.txt You can even combine the stdout and stderr streams using the file number and the & prefix. dir C:\ > lists.txt 2>&1

Suppressing Program Output

The pseudo-file NUL is used to discard the output of a program. The following example shows that the output of the dir command is discarded by sending it to NUL. dir C:\ > NUL

Stdin

To work with the stdin, a workaround must be used. This can be done by redirecting the command prompt stdin, called CON. The following example shows how you can redirect the output to a file called lists.txt. After you execute the below command, the command prompt will take all the input entered by user till it gets an EOF character. Later, it sends all the input to the file lists.txt. TYPE CON > lists.txt

Batch Script Return Code

 Return Code

By default, when the execution of a command line completes, it should return zero when the execution succeeds or non-zero when the execution fails. When a batch script returns a non-zero value after the execution fails, the non-zero value will indicate what is the error number. Note:The error number is used to determine the reason for the error and resolve it accordingly. The following table shows the most common exit codes and their description.
Error CodeDescription
0Program successfully completed.
1Incorrect function. Indicates that Action has attempted to execute non-recognized command in Windows command prompt cmd.exe.
2The system cannot find the file specified. Indicates that the file cannot be found in specified location.
3The system cannot find the path specified. Indicates that the specified path cannot be found.
5Access is denied. Indicates that user has no access right to specified resource.
9009 0x2331Program is not recognized as an internal or external command, operable program or batch file. Indicates that command, application name or path has been misspelled when configuring the Action.
221225495 0xC0000017 -1073741801Not enough virtual memory is available. It indicates that Windows has run out of memory.
3221225786 0xC000013A -1073741510The application terminated as a result of a CTRL+C. Indicates that the application has been terminated either by the user's keyboard input CTRL+C or CTRL+Break or closing command prompt window.
3221225794 0xC0000142 -1073741502The application failed to initialize properly. Indicates that the application has been launched on a Desktop to which the current user has no access rights. Another possible cause is that either gdi32.dll or user32.dll has failed to initialize.

 Environment Variable %ERRORLEVEL%

The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script. By default, the way to check for the ERRORLEVEL is via the following code. IF %ERRORLEVEL% NEQ 0 ( do_something ) It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file. Note: EXIT /B at the end of the batch file will stop execution of a batch file. Use EXIT /B <exitcodes> at the end of the batch file to return custom return codes. Note:In the batch file, it is always a good practice to use environment variables instead of constant values, since the same variable get expanded to different values on different computers.

Example

Consider the following batch script contained in a file called find.bat. If the file lists.txt is not found, you should set the error level code to 7. Similarly, if the userprofile variable is not defined, you should set the error level code to 9. find.bat if not exist c:\lists.txt exit 7 if not defined userprofile exit 9 exit 0 Let's assume we have another file called app.bat that calls find.bat first. If the find.bat file returns an error and sets the error level to a value greater than 0, the program exits. app.bat call Find.cmd if errorlevel gtr 0 exit echo “Successful completion” Output In the above program, the following scenarios can be obtained as output: If the file c:\lists.txt does not exist, nothing will be displayed in the console output. If the userprofile variable does not exist, nothing will be displayed in the console output. If both of the above conditions are passed, the command prompt will display the string "Successful completion".

Batch Script Loops

Loops

Like if-else statements, loops are used to alter the flow of program logic. "Looping" basically means performing a continuous operation until a certain condition is met. Note:In batch script, there is the direct implementation of for loop only. There does not exist while and do while loops as in other programming languages. There are several types of control flow instructions for loops that can be executed in Batch Script: While Loop For Loop in Lists For Loop in Ranges Classic Implementation of For Loop For Loop in Command Line Arguments Break in Loops

Batch Script Functions

A function is a set of instructions organized together to perform a specific task. More precisely, a function is a single complete unit (self-contained block) containing a block of code that performs a specific task. The function performs the same task when called which avoids the need of rewriting the same code again and again. Like in any other programming language, batch script functions also have: function definition function call Note:When defining the main program, it is necessary to ensure that the EXIT /B %ERRORLEVEL% statement is used in the main program to separate the main program code from the function.

Function Definition

In Batch Script, a function is defined using the label statement and followed by the code to be executed Function Syntax :function_name Some_Code EXIT /B 0 As shown in the syntax, there are three main parts in function definition in a batch file: You start by declaring a function with a label. Then there is the body of the function, where the codes to perform a given task are written. At the end EXIT /B 0 is used to ensure that functions terminate or exit correctly. The following is an example of a simple function. :Display SET /A index=2 echo The value of index is %index% EXIT /B 0

Function Call

In Batch Script a function is called by using the call command. :: To call function without parameters CALL :function_name :: To call function with parameters CALL :function_name param1, param2,...,paramN :: To call function with return values CALL :function_name return_value1,return_value2,..,return_valueN Note:To learn more about functions with parameters and recursive functions, see the following pages.

Batch Script File Input Output

In Batch Script you can perform the normal file I/O operations that you would expect in any programming language. Following are some of the operations that can performed on files. Creating files Reading files Writing to files Appending to files Deleting files Moving files Renaming files

Batch Script Folders

In Batch Script you can perform the normal folder-based operations that you would expect in any programming language. The following are some of the operations that can be performed on folders. Creating folders Listing folders Deleting folders Renaming folders Moving folders

Batch Script Process

Various Batch Script commands involving Windows processes will be discussed below.

 Viewing the List of Running Processes

In Batch Script, the tasklist command can be used to get the list of processes currently running in a system. Syntax tasklist[/s system [/u username [/p [password]]] [/m [module] | /svc | /v] [/fi filter] [/fo format] [/nh] The options that can be presented to the tasklist command are described below.
OptionDescription
/s systemSpecifies the remote system to connect to
/u [domain\]userSpecifies the user context under which the command should execute.
/p [password]Specifies the password for the given user context. Prompts for input if omitted.
/m [module]Lists all tasks currently using the given exe/dll name. If the module name is not specified all loaded modules are displayed.
/svcDisplays services hosted in each process.
/vDisplays verbose task information.
/fi filterDisplays a set of tasks that match a given criteria specified by the filter.
/fo formatSpecifies the output format. Valid values: TABLE, LIST, CSV.
/nhSpecifies that the "Column Header" should not show in the output. Valid only for TABLE and CSV formats.

Examples

The command below provides a list of all processes running on the local system: tasklist Image Name PID Session Name Session# Mem Usage ========================= ======== ================ =========== ============ System Idle Process 0 Services 0 4 K System 4 Services 0 272 K smss.exe 344 Services 0 1,040 K csrss.exe 528 Services 0 3,892 K csrss.exe 612 Console 1 41,788 K wininit.exe 620 Services 0 3,528 K winlogon.exe 648 Console 1 5,884 K services.exe 712 Services 0 6,224 K lsass.exe 720 Services 0 9,712 K svchost.exe 788 Services 0 10,048 K svchost.exe 832 Services 0 7,696 K dwm.exe 916 Console 1 117,440 K nvvsvc.exe 932 Services 0 6,692 K nvxdsync.exe 968 Console 1 16,328 K nvvsvc.exe 976 Console 1 12,756 K svchost.exe 1012 Services 0 21,648 K svchost.exe 236 Services 0 33,864 K svchost.exe 480 Services 0 11,152 K svchost.exe 1028 Services 0 11,104 K svchost.exe 1048 Services 0 16,108 K wlanext.exe 1220 Services 0 12,560 K conhost.exe 1228 Services 0 2,588 K svchost.exe 1276 Services 0 13,888 K svchost.exe 1420 Services 0 13,488 K spoolsv.exe 1556 Services 0 9,340 K Note:You not only get the various processes running on the system, but also the memory usage of each process. The following command kills the open notepad task, if open. taskkill /f /im notepad.exe The following command kills a process which has PID of 1234. taskill /pid 1234

 Killing a Particular Process

Batch Scripting also has the ability to start a new process. This is achieved by using the start command. start "title" [/d path] [options] "command" [parameters] where: title Text for the CMD window title bar (required.) path Starting directory. command The command, batch file or executable program to run. parameters The parameters passed to the command. Following are the description of the options which can be presented to the start command.
OptionsDescription
/minStart window Minimized
/maxStart window maximized.
/lowUse IDLE priority class.
/normalUse NORMAL priority class.
/abovenormalUse ABOVENORMAL priority class.
/belownormalUse BELOWNORMAL priority class.
/highUse HIGH priority class.
/realtimeUse REALTIME priority class.

Example

The following command will run the batch script test.bat in a new window. The windows will start in the minimized mode and also have the title of “Test Batch Script”. start "Test Batch Script" /Min test.bat The following command will actually run Microsoft Word in another process and then open the file test-a.txt in Microsoft Word. START "" "C:\Program Files\Microsoft Office\Winword.exe" "D:\test\test-a.txt"

 Starting a New Process

Example

Batch Script Alias

 Batch Script Alias

Alias means creating shortcuts or keywords for existing commands. Suppose we want to run the following command, which is nothing more than the directory list command with the /w option to not show all the necessary details in a directory list. dir /w Suppose if we were to create a shortcut to this command as follows. dw = dir /w When we want to execute the dir /w command, we can simply type in the word dw. The word dw has now become an alias to the command dir /w.

Creating an Alias

Alias are managed by using the doskey command. doskey [options] [macroname=[text]] where macroname: a short name for the macro. text: the commands you want to recall. Following are the description of the options which can be presented to the doskey command.
OptionsDescription
/reinstallInstalls a new copy of Doskey
/listsize = sizeSets size of command history buffer.
/macrosDisplays all Doskey macros.
/macros:allDisplays all Doskey macros for all executables which have Doskey macros.
/macros:exenameDisplays all Doskey macros for the given executable.
/historyDisplays all commands stored in memory.
/insertSpecifies that new text you type is inserted in old text.
/overstrikeSpecifies that new text overwrites old text.
/exename = exenameSpecifies the executable.
/macrofile = filenameSpecifies a file of macros to install.
macronameSpecifies a name for a macro you create.
textSpecifies commands you want to record.

Example

Create a new file called keys.bat and enter the following commands in the file. The below commands creates two aliases, one if for the cd command, which automatically goes to the directory called test. And the other is for the dir command. keys.bat @echo off doskey cd = cd/test doskey d = dir Once the command is executed, you will be able to run these aliases in the command prompt.

 Deleting an Alias

An alias or macro can be eliminated by setting the value of the macro to NULL.

Example

In the following example, we are first setting the macro d to d = dir. After which we are setting it to NULL. Because we have set the value of d to NULL, the macro d will be deleted. @echo off doskey cd = cd/test doskey d = dir d=

 Replacing an Alias

An alias or macro can be replaced by setting the value of the macro to the new desired value.

Example

In the above example, we are first setting the macro d to d = dir. After which we are setting it to dir /w. Since we have set the value of d to a new value, the alias d will now take on the new value. @echo off doskey cd = cd/test doskey d = dir d = dir /w

Batch Script Device Console

Windows now has an improved library which can be used in Batch Script for working with devices attached to the system. This is known as the device console or DevCon.exe. DevCon (Devcon.exe), the Device Console, is a command-line tool that displays detailed information about devices on computers running Windows. You can use DevCon to enable, disable, install, configure, and remove devices. Note: DevCon (DevCon.exe) is included when you install the WDK, Visual Studio, and the Windows SDK for desktop apps. DevCon.exe kit is available in the following locations when installed. %WindowsSdkDir%\tools\x64\devcon.exe %WindowsSdkDir%\tools\x86\devcon.exe %WindowsSdkDir%\tools\arm\devcon.exe

What Can DevCon Do?

Windows driver developers and testers can use DevCon to verify that a driver is properly installed and configured, including INF files, driver stack, driver files, and driver package. Note:DevCon is a command-line tool that performs device management functions on local computers. Devcon features include: Display driver and device info DevCon can display the following properties of drivers and devices on local computers: Hardware IDs, compatible IDs, and device instance IDs. These identifiers are described in detail in Device Identification Strings. Device setup classes The devices in a device setup class INF files and device driver files Details of driver packages Hardware resources Device status Expected driver stack Third-party driver packages in the driver store Search for devices DevCon can search for devices on a local computer by hardware ID, device instance ID, or device setup class. Change device settings DevCon can change the status or configuration of Plug and Play (PnP) devices on the local computer in the following ways: Enable a device Disable a device Update drivers (interactive and noninteractive) Install a device (create a devnode and install software) Remove a device from the device tree and delete its device stack Rescan for Plug and Play devices Add, delete, and reorder the hardware IDs of root-enumerated devices Change the upper and lower filter drivers for a device setup class Add and delete third-party driver packages from the driver store Restart the device or computer DevCon can restart a local device, reboot the local system on demand, or reboot the local system if required for another DevCon operation.

Syntax

devcon [/m:\\computer] [/r] command [arguments] where: /m:\\computer runs the command on the specified remote computer. The backslashes are required. /r conditional reboot. Reboots the system after completing an operation only if a reboot is required to make a change effective. command specifies a DevCon command. To list and display information about devices on the computer, use the following commands: DevCon HwIDs DevCon Classes DevCon ListClass DevCon DriverFilesv DevCon DriverNodes DevCon Resources DevCon Stack DevCon Status DevCon Dp_enum To search for information about devices on the computer, use the following commands: DevCon Find DevCon FindAll To manipulate the device or change its configuration, use the following commands: DevCon Enable DevCon Disable DevCon Update DevCon UpdateNI DevCon Install DevCon Removev DevCon Rescan DevCon Restart DevCon Reboot DevCon SetHwID DevCon ClassFilter DevCon Dp_add DevCon Dp_delete

Examples

Following are some examples on how the DevCon command is used. The following command uses the DevCon DriverFiles operation to list the names of driver files used by devices on the system. The command uses the wildcard character (*) to indicate all the devices in the system. Because the output is extensive, the command uses the redirect character (>) to redirect the output to a reference file, driverfiles.txt. devcon driverfiles * > driverfiles.txt The following command uses the DevCon status operation to find the status of all devices on the local computer. It then saves the status in the status.txt file for logging or later review. The command uses the wildcard character (*) to represent all devices and the redirect character (>) to redirect the output to the status.txt file. devcon status * > status.txt The following command enables all printing devices on the computer by specifying the Printer setting class in a DevCon Enable command. The command includes the parameter /r, which restarts the system if it is needed to make the enablement effective. devcon /r enable = Printer The following command uses the DevCon Install operation to install a keyboard device on the local computer. The command includes the full path to the INF file for the device (keyboard.inf) and a hardware ID (*PNP030b). devcon /r install c:\windows\inf\keyboard.inf *PNP030b The following command will scan the computer for new devices. devcon scan The following command will rescan the computer for new devices. devcon rescan

Batch Script Registry

The registry is one of the key elements of a Windows system. It contains a lot of information about various aspects of the operating system. Almost all applications installed on a Windows system interact with the registry. The Registry contains two basic elements: keys and values. Registry keys are container objects similar to folders. Registry values are non-container objects similar to files. Keys can contain values or other keys. Keys are referenced with a syntax similar to that of Windows path names, using backslashes to indicate hierarchical levels. Several types of registry operations can be performed: Reading from the Registry (via the REG QUERY command) Adding to the Registry (via the REG ADD command) Deleting from the Registry (via the REG DEL command) Copying Registry Keys (via the REG COPY command) Comparing Registry Keys (via the REG COMPARE command)

Batch Script Network

The batch script has the ability to work with network settings. The net command is used to update, correct or display the network or network settings. Several options are available for the net command:
CommandDescription
net accountsView the current password and logon restrictions for the computer.
net configDisplays your current server or workgroup settings.
net computerAdds or removes a computer attached to the windows domain controller.
net userThis command can be used to view the details of a particular user account, and add/delete/modify a user
net stop/startThis command is used to stop and start a particular service.
net statisticsDisplay network statistics of the workstation or server.
net useConnects or disconnects your computer from a shared resource or displays information about your connections.

Batch Script Printing

 Batch Script Printing

Bash script allows to control printing with the help of the net print command. The syntax of this command is given below: Sytax print [/d:print_device] [[drive:][path]filename[...]] where: print_device specifies a print device For example, the following command will print the example.txt file to the parallel port lpt1. print c:\example.txt /c /d:lpt1

 Command Line Printer Control

The Windows command-line tool can be used to manage most of the Windows configuration. For this purpose, the PRINTUI.DLL and RUNDLL32.EXE commands are used. The syntax is given below: RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry [option] [@commandfile] where the options available are the following: /dl used to delete the local printer /dn used to delete network printer connection. /dd used to delete the printer driver. /e shows printing preferences. f[file] either inf file or output file. /F[file] location of an INF file that the INF file specified with /f may depend on. /ia installs printer driver using inf file. /id installs printer driver using add printer driver wizard. /if installs printer using inf file. /ii installs printer using add printer wizard with an inf file. /il installs printer using add printer wizard. /in adds network printer connection. /ip installs printer using network printer installation wizard. /k prints test page to specified printer, cannot be combined with command when installing a printer. /l[path] printer driver source path. /m[model] printer driver model name. /n[name] printer name. /o display printer queue view. /p displays printer properties. /Ss stores printer settings into a file. /Sr restores printer settings from a file. /y sets printer as the default. /Xg gets printer settings. /Xs sets printer settings.

 Testing if a Printer Exists

It may happen that you are connected to a network printer instead of a local printer. In such cases, it is always useful to check for a printer before printing. Note:The existence of a printer can be evaluated with the help of the RUNDLL32.EXE PRINTUI.DLL. In the following example, we will first set the printer name and set a file name which will hold the settings of the printer. Then RUNDLL32.EXE PRINTUI.DLL commands will be used to check if the printer actually exists by sending the configuration settings of the file to the file TR-Printers.txt SET PrinterName = Test Printer SET file=%TEMP%\TR-Printers.txt RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry /Xg /n "%PrinterName%" /f "%file%" /q IF EXIST "%file%" ( ECHO %PrinterName% printer exists ) ELSE ( ECHO %PrinterName% printer does NOT exists )

Batch Script Debugging

Debugging is important because it allows to discover and to fix errors in a program before releasing it to the public. As in any programming language, debugging is also possible in batch scripts. You can debug in different ways: Using echo command Using pause command Logging the error messages to another file Using ErrorLevel to detect errors and log them

Using echo command

The easiest way to debug is to use the echo command in batch scripts. It will display the message in the command prompt and help you debug where things have gone wrong. In the following example example-echo.bat @echo off if [%1] == [] ( echo input value not provided goto stop ) rem Display numbers for /l %%n in (2,2,%1) do ( echo %%n ) :stop pause C:\>example-echo.bat 10 2 4 6 8 10 22 Press any key to continue ...

Using pause command

Another way is to pause batch execution when an error occurs. When the script is paused, the developer can fix the problem and restart processing. In the following example, the batch script is paused because the input value is mandatory and is not provided. example-pause.bat @echo off if [%1] == [] ( echo input value not provided goto stop ) else ( echo "Valid value" ) :stop pause C:\>example-pause.bat input value not provided Press any key to continue..

Logging the error messages to another file

It may be difficult to debug the error just by looking at a bunch of echoes displayed in the command prompt. Another simple solution is to record the messages in another file and view them step by step to understand what went wrong. For example, the command given in the .bat file is wrong: example-log.bat net statistics /Server so we can log it and then see what we get: C:\>example-log.bat > testlog.txt 2> testerrors.txt The file testerrors.txt will display the error messages as shown below: The option /SERVER is unknown. The syntax of this command is: NET STATISTICS [WORKSTATION | SERVER] More help is available by typing NET HELPMSG 3506. Note:Looking at the testlog.txt and testerrors.txt files the developer can fix the program and execute again.

Using ErrorLevel to detect errors and log them

Errorlevel returns 0 if the command executes successfully and 1 if it fails. Consider the following example: example-errorelevel.bat @echo off PING google.com if errorlevel 1 GOTO stop :stop echo Unable to connect to google.com pause During execution, you can see errors as well as logs: C:\>example-errorelevel.bat > testlog.txt And the output is inside the textlog.txt file: Pinging google.com [172.217.26.238] with 32 bytes of data: Reply from 172.217.26.238: bytes=32 time=160ms TTL=111 Reply from 172.217.26.238: bytes=32 time=82ms TTL=111 Reply from 172.217.26.238: bytes=32 time=121ms TTL=111 Reply from 172.217.26.238: bytes=32 time=108ms TTL=111 Ping statistics for 172.217.26.238: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 82ms, Maximum = 160ms, Average = 117ms Connected successfully Press any key to continue . . . In case of failure, you will see the following logs inside testlog.txt. Ping request could not find host google.com. Please check the name and try again. Unable to connect to google.com Press any key to continue . . .

Batch Script Logging

In Batch Script, logging is possible by using the redirection command. Syntax example.bat > examplelog.txt 2> exampleerrors.txt

Example

For example, create a file called example.bat and enter the following command in the file: net statistics /Server The previous command has an error because the net statistics command option was given incorrectly. So, if the command with the above example.bat file is run as: example.bat > examplelog.txt 2> exampleerrors.txt And you open the file exampleerrors.txt, you will see the following error. The option /SERVER is unknown. The syntax of this command is: NET STATISTICS [WORKSTATION | SERVER] More help is available by typing NET HELPMSG 3506. If you open the file called examplelog.txt, it will show you a log of what commands were executed: C:\>net statistics /Server

Introduction

This book addresses 32-bit Windows commands applicable to modern versions of Windows based on the Windows NT environment. It does not address commands that are specific to DOS environments and to DOS-based operating systems, such as Windows 95, Windows 98, and Windows Me, whose Microsoft-supplied command interpreters are in fact DOS programs, not Win32 programs. You can find out which version of cmd.exe you are running using the VER command. This book first describes using the Windows NT command interpreter, how it receives, parses, and processes commands from users. Then it describes various commands available. To obtain an extensive list of Windows commands and their short summaries, open the command prompt on any Windows computer, and type help. To find out about a particular command, type the name of the command followed by "/?". The subject of this book is also known as "batch programming", even though "batch" refers not only to batch files for MS DOS and Windows command interpreter. Other subject terms include "batch file programming", "batch file scripting", "Windows batch command", "Windows batch file", "Windows command line", "Windows command prompt", and "Windows shell scripting".

Using the Windows command interpreter

How a command line is interpreted

The parsing of a command line into a sequence of commands is complex, and varies subtly from command interpreter to command interpreter. There are, however, four main components:
Variable substitution
A command line is scanned for variable specifications, and any found are replaced with the contents of those variables.
Quoting
Special characters can be quoted, to remove their special meanings.
Syntax
Command lines are developed into a sequence of commands according to a syntax.
Redirection
Redirection specifications are applied, and removed from the command line, before an individual command in a sequence is executed.

Variable substitution

Command lines can contain variable specifications. These comprise a % character followed by a name. The name is ended by a second % character, except in special cases such as the batch file parameters %1, %2, and so forth. Variable specifications are replaced with values. The value used to replace a variable specification is as follows: For variable specification names that match the names of environment variables, the replacement is the value of the named environment variable. For example: %PATH% is replaced by the value of the PATH environment variable. For variable specifications that name batch file parameters (i.e. that are non-negative decimal numbers), the replacement is the value of the parameter taken from the arguments with which the batch file was invoked (subject to any subsequent modifications by the SHIFT command). For example: %2 is replaced by the value of the second batch file parameter.
Special names
Some variable names are not visible using SET command. Rather, they are made available for reading using the% notation. To find out about them, type "help set". Special variable names and what they expand to:
NameReplacement Value Used
%CD%The current directory, not ending in a slash character if it is not in the root directory of the current drive
%TIME%The system time in HH:MM:SS.mm format.
%DATE%The system date in a format specific to localization.
%RANDOM%A generated pseudo-random number between 0 and 32767.
%ERRORLEVEL%The error level returned by the last executed command, or by the last called batch script.
%CMDEXTVERSION%The version number of the Command Processor Extensions currently used by cmd.exe.
%CMDCMDLINE%The content of the command line used when the current cmd.exe was started.

Quoting and escaping

You can prevent the special characters that control command syntax from having their special meanings as follows, except for the percent sign (%): You can surround a string containing a special character by quotation marks. You can place caret (^), an escape character, immediately before the special characters. In a command located after a pipe (|), you need to use three carets (^^^) for this to work. The special characters that need quoting or escaping are usually <, >, |, &, and ^. In some circumstances,! and \ may need to be escaped. A newline can be escaped using caret as well. When you surround the string using quotation marks, they become part of the argument passed to the command invoked. By contrast, when you use caret as an escape character, the caret does not become part of the argument passed. The percent sign (%) is a special case. On the command line, it does not need quoting or escaping unless two of them are used to indicate a variable, such as%OS%. But in a batch file, you have to use a double percent sign (%%) to yield a single percent sign (%). Enclosing the percent sign in quotation marks or preceding it with caret does not work. Examples echo "Johnson & son" Echoes the complete string rather than splitting the command line at the & character. Quotes are echoed as well echo Johnson ^& son As above, but using caret before the special character ampersand. No quotes are echoed. echo Johnson & son Does not use an escape character and therefore, "son" is interpreted as a separate command, usually leading to an error message that command son is not found. echo A ^^ B Echoes A ^ B. Caret needs escaping as well or else it is interpreted as escaping a space. if 1 equ 1 ^ echo Equal &^ echo Indeed, equal Echoes the two strings. The caret at the end of the line escapes the newlines, leading to the three lines being treated as if they were a single line. The space before the first caret is necessary or else 1 gets joined with the following echo to yield 1echo. attrib File^ 1.txt Does not shows attributes of file named "File 1.txt" since escaping of space does not work. Using quotes, as in attrib "File 1.txt", works. echo The ratio was 47%. If run from a batch, the percent sign is ignored. echo The ratio was 47%%. If run from a batch, the percent sign is output once. set /a modulo=14%%3 If run from a batch, sets modulo variable to 2, the remainder of dividing 14 by 3. Does not work with single%. for %%i in (1,2,3) do echo %%i If run from a batch, outputs 1, 2 and 3. echo %temp% Outputs the content of temp variable even if run from a batch file. Use of the percent sign in a batch to access environment variables and passed arguments needs no escaping. echo //comment line | findstr \// Command FINDSTR uses backslash (\) for espacing. Unlike caret, this is internal to the command and unknown to the command shell.

Syntax

Command lines are developed into a sequence of commands according to a syntax. In that syntax, simple commands may be combined to form pipelines, which may in turn be combined to form compound commands, which finally may be turned into parenthesized commands. A simple command is just a command name, a command tail, and some redirection specifications. An example of a simple command is dir *.txt > somefile. A pipeline is several simple commands joined together with the "pipe" metacharacter—"|", also known as the "vertical bar". The standard output of the simple command preceding each vertical bar is connected to the standard input of the simple command following it, via a pipe. The command interpreter runs all of the simple commands in the pipeline in parallel. An example of a pipeline (comprising two simple commands) is dir *.txt | more. A compound command is a set of pipelines separated by conjunctions. The pipelines are executed sequentially, one after the other, and the conjunction controls whether the command interpreter executes the next pipeline or not. An example of a compound command (comprising two pipelines, which themselves are just simple commands) is move file.txt file.bak && dir > file.txt. The conjunctions: & - An unconditional conjunction. The next pipeline is always executed after the current one has completed executing. && - A positive conditional conjunction. The next pipeline is executed if the current one completes executing with a zero exit status. || - A negative conditional conjunction. The next pipeline is executed if the current one completes executing with a non-zero exit status. A parenthesized command is a compound command enclosed in parentheses (i.e. ( and )). From the point of view of syntax, this turns a compound command into a simple command, whose overall output can be redirected. For example: The command line ( pushd temp & dir & popd ) > somefile causes the standard output of the entire compound command ( pushd temp & dir & popd ) to be redirected to somefile.

Redirection

Redirection specifications are applied, and removed from the command line, before an individual command in a sequence is executed. Redirection specifications control where the standard input, standard output, and standard error file handles for a simple command point. They override any effects to those file handles that may have resulted from pipelining. (See the preceding section on command syntax.) Redirection signs > and >> can be prefixed with 1 for the standard output (same as no prefix) or 2 for the standard error. The redirection specifications are:
< filename
Redirect standard input to read from the named file.
> filename
Redirect standard output to write to the named file, overwriting its previous contents.
>> filename
Redirect standard output to write to the named file, appending to the end of its previous contents.
>&h
Redirect to handle h, where handle is any of 0—standard input, 1—standard output, 2—standard error, and more.
<&h
Redirect from handle h.
Examples: dir *.txt >listing.log Redirects the output of the dir command to listing.log file. dir *.txt > listing.log As above; the space before the file name makes no difference. However, if you type this into the command window, auto-completion with tab after typing "> l" actually works, while it does not work with ">listing.log". dir *.txt 2>NUL Redirects errors of the dir command to nowhere. dir *.txt >>listing.log Redirects the output of the dir command to listing.log file, appending to the file. Thereby, the content of the file before the redirected command was executed does not get lost. dir *.txt >listing.log 2>&1 Redirects the output of the dir command to listing.log file, along with the error messages. dir *.txt >listing.log 2>listing-errors.log Redirects the output of the dir command to listing.log file, and the error messages to listing-errors.log file. >myfile.txt echo Hello The redirection can precede the command. echo Hello & echo World >myfile.txt Only the 2nd echo gets redirected. (echo Hello & echo World) >myfile.txt Output of both echos gets redirected. type con >myfile.txt Redirects console input (con) to the file. Thus, allows multi-line user input terminated by user pressing Control + Z. See also #User input. (for %i in (1,2,3) do @echo %i) > myfile.txt Redirects the entire output of the loop to the file. for %i in (1,2,3) do @echo %i > myfile.txt Starts redirection anew each time the body of the loop is entered, losing the output of all but the latest loop iteration.

How a command is executed

(...)

Batch reloading

The command interpreter reloads the content of a batch after each execution of a line or a bracketed group. If you start the following batch and change "echo A" to "echo B" in the batch shortly after starting it, the output will be B. @echo off ping -n 6 127.0.0.1 >nul & REM wait echo A What is on a single line does matter; changing "echo A" in the following batch after running it has no impact: @echo off ping -n 6 127.0.0.1 >nul & echo A Nor have after-start changes have any impact on commands bracketed with ( and ). Thus, changing "echo A" after starting the following batch has no impact: @echo off for /L %%i in (1,1,10) do ( echo A ping -n 2 127.0.0.1 >nul & REM wait ) Ditto for any other enclosing, including this one: @echo off ( ping -n 6 127.0.0.1 >nul & REM wait echo A )

Environment variables

The environment variables of the command interpreter process are inherited by the processes of any (external) commands that it executes. A few environment variables are used by the command interpreter itself. Changing them changes its operation. Environment variables are affected by the SET, PATH, and PROMPT commands. To unset a variable, set it to empty string, such as "set myvar=". The command interpreter inherits its initial set of environment variables from the process that created it. In the case of command interpreters invoked from desktop shortcuts this will be Windows Explorer, for example. Command interpreters generally have textual user interfaces, not graphical ones, and so do not recognize the Windows message that informs applications that the environment variable template in the Registry has been changed. Changing the environment variables in Control Panel will cause Windows Explorer to update its own environment variables from the template in the Registry, and thus change the environment variables that any subsequently invoked command interpreters will inherit. However, it will not cause command interpreters that are already running to update their environment variables from the template in the Registry.

COMSPEC

The COMSPEC environment variable contains the full pathname of the command interpreter program file. This is just inherited from the parent process, and is thus indirectly derived from the setting of COMSPEC in the environment variable template in the Registry.

PATH

The value of the PATH environment variable comprises a list of directory names, separated by semi-colon characters. This is the list of directories that are searched, in order, when locating the program file of an external command to execute.

PATHEXT

The value of the PATHEXT environment variable comprises a list of filename extensions, separated by semi-colon characters. This is the list of filename extensions that are applied, in order, when locating the program file of an external command to execute. An example content of PATHEXT printed by "echo %PATHEXT%": .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC By adding ".PL" to the variable, you can ensure Perl programs get run from the command line even when typed without the ".pl" extension. Thus, instead of typing "mydiff.pl a.txt b.txt", you can type "mydiff a.txt b.txt". Adding ".PL" to the variable in Windows Vista and later: setx PATHEXT%PATHEXT%;.PL If you use "set" available in Windows XP, the effect will be temporary and impacting only the current console or process.

PROMPT

The PROMPT environment variable controls the text emitted when the command interpreter displays the prompt. The command interpreter displays the prompt when prompting for a new command line in interactive mode, or when echoing a batch file line in batch file mode. Various special character sequences in the value of the PROMPT environment variable cause various special effects when the prompt is displayed, as in the following table:
CharactersExpansion Result
$$$ character itself
$A& symbol AKA ampersand. A convenience, since it is difficult to place a literal & in the value of the PROMPT environment variable using the SET command.
$BVertical bar '|' (pipe symbol)
$CLeft parenthesis '('
$DCurrent date
$EESC (ASCII code 27)
$FRight parenthesis ')'
$GGreater-than symbol '>'
$HBackspace (deletes previous character)
$LLess-than symbol '<'
$MRemote name linked to the current drive if it is a network drive; empty string otherwise.
$NCurrent drive letter
$PCurrent drive letter and full path
$Q'=' (equals sign)
$S' ' (space character)
$TCurrent system time
$VWindows version number
$_<CR> (carriage return character, aka "enter")
$+As many plus signs (+) as there are items on the pushd directory stack

Switches

Most Windows commands provide switches AKA options to direct their behavior. Observations: Switches most often consist of a single-letter; some switches consist of a sequence of multiple letters. Switches are preceded with a slash (/) rather than, as in some other operating systems, with a minus sign (-). Switches are case-insensitive rather than, as in some other operating systems, case-sensitive. If a command from another operating system is ported to Windows (such as grep), it usually retains the option conventions from the original operating system, including the use of minus sign and case-sensitivity. Examples: dir /? Displays the help. This option is provided by many commands. dir /b /s Lists all files and folders in the current folder recursively. Two switches are used: b and s. dir /bs Does not work; switches cannot be accumulated behind a single slash. findstr /ric:"id: *[0-9]*" File.txt Unlike many other commands, findstr allows the accumulation of switches behind a single slash. Indeed, r, i and c are single-letter switches. dir/b/s Works. In dir, removing whitespace between the command and the first switch or between the switches does not make a difference; thus, does the same as dir /b /s. tree/f/a Does not work, unlike tree /f /a. In tree, separation by whitespace is mandatory. Nor does find/i/v work. dir /od The switch letter o is further modified by a single letter specifying that ordering should be by date. The letter d is not a switch by itself. Similar cases include dir /ad and more /t4. dir /B /S The switches are case-insensitive, unlike in some other operating systems. sort /r file.txt Sorts the file in a reverse order. sort /reverse file.txt Sort allows the switch string to be longer than a single-letter. sort /reve file.txt Sort allows the specified switch string to be a substring of the complete long name of the switch. Thus, does the same as the above. sort /reva file.txt Does not work, since "reva" is not a substring of "reverse". taskkill /im AcroRd32.exe Taskkill requires a multiletter switch name for /im; shortening to /i does not work. java -version Java, which originated in the environment of another operating system family, uses the minus convention for its switches AKA options. grep --help If GNU grep is installed, it requires multi-letter switches to be preceded by two dashes.

Error level

Commands usually set error level at the end of their execution. In Windows NT and later, it is a 32-bit signed integer; in MS DOS, it used to be an integer from 0 to 255. Keywords: return code, exit code, exit status. The conventional meaning of the error level: 0 - success not 0 - failure The error levels being set are usually positive. If the command does not distinguish various kinds of failure, the error level on failure is usually 1. Uses of the error level: It can be tested using && and ||; see also #Syntax. It can be tested using IF. The value can be accessed from ERRORLEVEL variable. Examples: dir >NUL && echo Success The part after && is executed only if the error level is zero. color 00 || echo Failure The part after || is executed only if the error level is non-zero, whether positive or negative. color 00 || ( echo Failure ) Multiline bracketing works as well. echo %ERRORLEVEL% Displays the error level without changing it. if%errorlevel% equ 0 echo The error level is zero, meaning success. if%errorlevel% neq 0 echo The error level is non-zero, meaning failure. if errorlevel 1 echo The error level is >= 1, meaning failure via positive error level. Does not cover failure via negative error level. Note the ">=" part: this is not the same as if%errorlevel% equ 1. exit /b 1 Returns a batch file, setting the error level to 1. cmd /c "exit /b 10" In the middle of a batch file or on the command line, sets the error level to 10. (cmd /c "exit /b 0" && Echo Success) & (cmd /c "exit /b -1" || Echo Failure) As above, showing the error level is indeed affected. (cmd /c "exit /b 0" & cmd /c "exit /b 1") || Echo Failure The error level of a chain created by & is the error level of the last command of the chain. cmd /c "exit /b -1" & if not errorlevel 1 echo Would-be success The "if not errorlevel 1" test, which might appear to test for success, passes on negative numbers: it tests on "not error level >= 1", which is "error level <= 0". set myerrorlevel=%errorlevel% Remembers the error level for later. set errorlevel=0 To be avoided: overshadows the built-in errorlevel variable. Ensures that subsequent accesses via%ERRORLEVEL% return 0 rather than the actual error level. cmd /c "exit /b 0" if 1 equ 1 ( cmd /c "exit /b 1" & echo %errorlevel% ) Displays 0, since%errorlevel% gets expanded before cmd /c "exit /b 1" gets executed.

String processing

Getting a substring of a variable by position and length: Before running the following examples, ensure that%a% equals "abcd" by running this: set a=abcd The examples: echo %a:~0,1% Result: a echo %a:~1,1% Result: b echo %a:~0,2% Result: ab echo %a:~1,2% Result: bc echo %a:~1% Result: bcd echo %a:~-1% Result: d echo %a:~-2% Result: cd echo %a:~0,-2% Result: ab echo %a:~0,-1% Result: abc echo %a:~1,-1% Result: bc Testing substring containment: if not "%a:bc=%"=="%a%" echo yes If variable a contains "bc" as a substring, echo "yes". This test is a trick that uses string replacement, discussed below. This test does not work if the variable contains a quotation mark. Testing for "starts with": if%a:~0,1%==a echo yes If variable a starts with "a", echo "yes". if%a:~0,2%==ab echo yes If variable a starts with "ab", echo "yes". String replacement: set a=abcd & echo %a:c=% Result: abd set a=abcd & echo %a:c=e% Result: abed set a=abcd & echo %a:*c=% Result: d The asterisk only works at the beginning of the sought pattern; it does not work at the end or in the middle. See also the help for SET command: set /?. Splitting a string by any of " ", ",", and ";": ["space", "comma" and "semicolon":]
set myvar=a b,c;d
for %%a in (%myvar%) do echo %%a
Splitting a string by semicolon, assuming the string contains no quotation marks: @echo off set myvar=a b;c;d set strippedvar=%myvar% :repeat for /f "delims=;" %%a in ("%strippedvar%") do echo %%a set prestrippedvar=%strippedvar% set strippedvar=%strippedvar:*;=% if not "%prestrippedvar:;=%"=="%prestrippedvar%" goto :repeat

Command-line arguments

The command-line arguments AKA command-line parameters passed to a batch script are accessible as%1,%2, ...,%9. There can be more than nine arguments; to access them, see how to loop over all of them below. The syntax%0 does not refer to a command-line argument but rather to the name of the batch file. Testing for whether the first command-line argument has been provided: if not -%1-==--echo Argument one provided if -%1-==--echo Argument one not provided & exit /b A robust looping over all command-line arguments using SHIFT (for each command-line argument, ...): :argactionstart if -%1-==-- goto argactionend echo %1 & REM Or do any other thing with the argument shift goto argactionstart :argactionend A robust looping over all command-line arguments using SHIFT without modifying%1,%2, etc.: call :argactionstart %* echo Arg one: %1 & REM %1, %2, etc. are unmodified in this location exit /b :argactionstart if -%1-==-- goto argactionend echo %1 & REM Or do any other thing with the argument shift goto argactionstart :argactionend exit /b Transferring command-line arguments to environment variables: setlocal EnableDelayedExpansion REM Prevent affecting possible callers of the batch REM Without delayed expansion, !arg%argno%! used below won't work. set argcount=0 :argactionstart if -%1-==-- goto argactionend set /a argcount+=1 set arg%argcount%=%1 shift goto argactionstart :argactionend set argno=0 :loopstart set /a argno+=1 if %argno% gtr %argcount% goto loopend echo !arg%argno%! & REM Or do any other thing with the argument goto loopstart :loopend Looping over all command-line arguments, albeit not a robust one: for %%i in (%*) do ( echo %%i ) This looks elegant but is non-robust, maltreating arguments containing wildcards (*,?). In particular, the above for command replaces arguments that contain wildcards (*,?) with file names that match them, or drops them if no files match. Nonetheless, the above loop works as expected as long as the passed arguments do not contain wildcards. Finding the number of command-line arguments, in a non-robust way: set argcount=0 for %%i in (%*) do set /a argcount+=1 Again, this does not work with arguments containing wildcards. The maximum possible number of arguments is greater than 4000, as empirically determined on a Windows Vista machine. The number can differ on Windows XP and Windows 7. In passing arguments to a batch script, characters used for argument separation are the following ones: space comma semicolon equal sign tab character Thus, the following lines pass the same four arguments: test.bat a b c d test.bat a,b,c,d test.bat a, b, c, d test.bat a;b;c;d test.bat a=b=c=d test.bat a b,c;,;=d Yes, even the line with "a b,c;,;=d" passes four arguments, since a sequence of separating characters is considered a single separator. To have a space, comma or semicolon in the argument value, you can pass the value enclosed in quotation marks. However, the quotation marks become part of the argument value. To get rid of the enclosing quotation marks when referring to the argument in the script, you can use%~<number> described in #Percent tilde.

Wildcards

Many commands accept file name wildcards--characters that do not stand for themselves and enable matching of a group of filenames. Wildcards: * (asterisk): any sequence of characters ? (question mark): a single character other than a period (".") or, if part of a sequence of question marks at the end of a maximum period-free part of a file name, possibly zero number of characters; see examples for clarification Examples: dir *.txt Matches Myfile.txt, Plan.txt and any other file with the .txt extension. dir *txt The period does not need to be included. However, this will also match files named without the period convention, such as myfiletxt. ren *.cxx *.cpp Renames all files with .cxx extension to have .cpp extension. dir a?b.txt Matches files aab.txt, abb.txt, a0b.txt, etc. Does not match ab.txt, since a question mark followed by a character other than a question mark or period cannot match zero characters. Does not match a.b.txt, since a question mark cannot match a period. dir???.txt Matches .txt, a.txt, aa.txt, and aaa.txt, among others, since each question mark in the sequence followed by a period can match zero number of characters. dir a???.b???.txt??? Matches a.b.txt, among others. While the last question mark sequence is not followed by a period, it is still a sequence at the end of a maximum period-free part of a file name. dir????????.txt & @REM eight question marks Matches the same files as *.txt, since each file also has a short file name that has no more than 8 characters before .txt. Quirk with short file names: the wildcard matching is performed both on long file names and the usually hidden short 8 chars + period + 3 chars file names. This can lead to bad surprises. Unlike shells of some other operating systems, the cmd.exe shell does not perform wildcard expansion (replacement of the pattern containing wildcards with the list of file names matching the pattern) on its own. It is the responsibility of each program to treat wildcards as such. This enables such things as "ren *.txt *.bat", since the ren command actually sees the * wildcard rather than a list of files matching the wildcard. Thus, "echo *.txt" does not display files in the current folder matching the pattern but rather literally displays "*.txt". Another consequence is that you can write "findstr a.*txt" without fearing that the "a.*txt" part gets replaced with the names of some files in the current folder. Furthermore, recursive "findstr /s pattern *.txt" is possible, while in some other operating systems, the "*.txt" part would get replaced with the file names found in the current folder, disregarding nested folders. Commands accepting wildcards include ATTRIB, COPY, DIR, FINDSTR, FOR, REN, etc.

User input

You can get input from the user using the following methods: SET /P command CHOICE command Using "type con >myfile.txt", for which the multi-line user input is terminated by user pressing Control + Z.

Percent tilde

When a command-line argument contains a file name, special syntax can be used to get various information about the file. The following syntaxes expand to various information about the file passed as%1:
SyntaxExpansion ResultExample
%~1%1 with no enclosing quotation marksNot provided
%~f1Full path with a drive letterC:\Windows\System32\notepad.exe
%~d1Drive letterC:
%~p1Drive-less path with the trailing backslash\Windows\System32\
%~n1For a file, the file name without path and extension For a folder, the folder name notepad
%~x1File name extension including the period.exe
%~s1Modify of f, n and x to use short nameNot provided
%~a1File attributes--a------
%~t1Date and time of last modification of the file02.11.2006 11:45
%~z1File size151040
%~pn1A combination of p and n\Windows\System32\notepad
%~dpnx1A combination of several lettersC:\Windows\System32\notepad.exe
%~$PATH:1The full path of the first match found in the folders present in the PATH variable, or an empty string in no match.
%~n0%~n applied to%0: The extensionless name of the batch tildetest
%~nx0%~nx applied to%0: The name of the batch tildetest.bat
%~d0%~f applied to%0: The drive letter of the batch C:
%~dp0%~dp applied to%0: The folder of the batch with trailing backslash C:\Users\Joe Hoe\
The same syntax applies to single-letter variables created by FOR command, such as "%%i". To learn about this subject from the command line, type "call /?" or "for /?".

Functions

Functions AKA subprograms can be emulated using CALL, labels, SETLOCAL and ENDLOCAL. An example of a function that determines arithmetic power: @echo off call :power 2 4 echo %result% rem Prints 16, determined as 2 * 2 * 2 * 2 goto :eof rem __Function power______________________ rem Arguments: %1 and %2 :power setlocal set counter=%2 set interim_product=%1 :power_loop if %counter% gtr 1 ( set /a interim_product=interim_product * %1 set /a counter=counter - 1 goto :power_loop ) endlocal & set result=%interim_product% goto :eof While the goto:eof at the end of the function is not really needed, it has to be there in the general case in which there is more than one function. The variable into which the result should be stored can be specified on the calling line as follows: @echo off call :sayhello result=world echo %result% exit /b :sayhello set %1=Hello %2 REM Set %1 to set the returning value exit /b In the example above, exit /b is used instead of goto:eof to the same effect. Also, remember that the equal sign is a way to separate parameters. Thus, the following items achieve the same: call:sayhello result=world call:sayhello result world call:sayhello result,world call:sayhello result;world (See Command-line arguments as a reminder)

Calculation

Batch scripts can do simple 32-bit integer arithmetic and bitwise manipulation using SET /a command. The largest supported integer is 2147483647 = 2 ^ 31 - 1. The smallest supported integer is -2147483648 = - (2 ^ 31), assignable with the trick of set /a num=-2147483647-1. The syntax is reminiscent of the C language. Arithmetic operators include *, /,% (modulo), +, -. In a batch, modulo has to be entered as "%%". Bitwise operators interpret the number as a sequence of 32 binary digits. These are ~ (complement), & (and), | (or), ^ (xor), << (left shift), >> (right shift). A logical operator of negation is!: it turns zero into one and non-zero into zero. A combination operator is ,: it allows more calculations in one set command. Combined assignment operators are modeled on "+=", which, in "a+=b", means "a=a+b". Thus, "a-=b" means "a=a-b". Similarly for *=, /=,%=, &=, ^=, |=, <<=, and >>=. The precedence order of supported operators, is as follows:
    ( ) * /% + - << >> & ^ | = *= /=%= += -= &= ^= |= <<= >>= ,
Literals can be entered as decimal (1234), hexadecimal (0xffff, leading 0x), and octal (0777, leading 0). The internal bit representation of negative numbers is two's complement. This provides a connection between arithmetic operations and bit operations. For instance, -2147483648 is represented as 0x80000000, and therefore set /a num=~(-2147483647-1) yields 2147483647, which equals 0x7FFFFFFF (type set /a num=0x7FFFFFFF to check). As some of the operators have special meaning for the command interpreter, an expression using them needs to be enclosed in quotation marks, such as this: set /a num="255^127" set /a "num=255^127" Alternative placement of quotation marks. set /a num=255^^127 Escape ^ using ^ instead of quotation marks. Examples: set n1=40 & set n2=25 set /a n3=%n1%+%n2% Uses the standard percent notation for variable expansion. set n1=40 & set n2=25 set /a n3=n1+n2 Avoids the percent notation around variable names as unneeded for /a. set /a num="255^127" Encloses "^" in quotation marks to prevent its special meaning for the command interpreter. set /a n1 = (10 + 5)/5 The spaces around = do not matter with /a. However, getting used to it lends itself to writing "set var = value" without /a, which sets the value of "var " rather than "var". set /a n1=2+3,n2=4*7 Performs two calculations. set /a n1=n2=2 Has the same effect as n1=2,n2=2. set n1=40 & set n2=25 & set /a n3=n1+n2 Works as expected. set /a n1=2,n2=3,n3=n1+n2 Works as expected. set n1=40 & set n2=25 & set /a n3=%n1%+%n2% Does not work unless n1 and n2 were set previously. The variable specifications "%n1%" and "%n2"% get expanded before the first set command is executed. Dropping percent notation makes it work. set /a n1=2,n2=3,n3=%n1%+%n2% Does not work unless n1 and n2 were set previously, for the reason stated in the previous example. set /a n1=0xffff Sets n1 using hexadecimal notation. set /a n1=0777 Sets n1 using octal notation. An example calculation that prints prime numbers: @echo off setlocal set n=1 :print_primes_loop set /a n=n+1 set cand_divisor=1 :print_primes_loop2 set /a cand_divisor=cand_divisor+1 set /a cand_divisor_squared=cand_divisor*cand_divisor if %cand_divisor_squared% gtr %n% echo Prime %n% & goto :print_primes_loop set /a modulo=n%%cand_divisor if %modulo% equ 0 goto :print_primes_loop & REM Not a prime goto :print_primes_loop2

Finding files

Files can be found using #DIR, #FOR, #FINDSTR, #FORFILES, and #WHERE. Examples: dir /b /s *base*.doc* Outputs all files in the current folder and its subfolders such that the file name before the extension contains the word "base" and whose extension starts with "doc", which includes "doc" and "docx". The files are output with full paths, one file per line. dir /b /s *.txt | findstr /i pers.*doc Combines the result of outputting files including their complete paths with the findstr filtering command supporting limited regular expressions, yielding a versatile and powerful combination for finding files by names and the names of their directories. for /r%i in (*) do @if%~zi geq 1000000 echo %~zi%i For each file in the current folder and its subfolders that has the size greater than or equal to 1,000,000 bytes, outputs the file size in bytes and the full path of the file. For the syntax in%~zi, see #Percent tilde. forfiles /s /d 06/10/2015 /c "cmd /c echo @fdate @path" For each file in the current folder and its subfolders modified on 10 June 2015 or later, outputs the file modification date and full file path. The date format after /d is locale specific. Thus, allows to find most recently modified files. (for /r%i in (*) do @echo %~ti::%i) | findstr 2015.*:: Searching the current folder recursively, outputs files whose last modification date is in year 2015. Places the modification date and time, followed by a double colon, before the file name. Works as long as the used version of Windows and locale displays dates in a format that contains four-digit years. The double colon is used to make sure the findstr command is matching the date and not the file name. for /r%i in (*) do @echo %~ti | findstr 2015 >NUL && echo %i As above, outputs files changed in 2015. Unlike the above, only outputs the files, not the modification dates. findstr /i /s /m cat.*mat *.txt Finds files by their content. Performs a full text search for regular expression cat.*mat in files with names ending in .txt, and outputs the files names. The /m switch ensures only the file names are output. where *.bat Outputs all .bat files in the current directory and in the directories that are in PATH.

Keyboard shortcuts

When using Windows command line from the standard console that appears after typing cmd.exe after pressing Windows + R, you can use multiple keyboard shortcuts, including function keys: Tab: Completes the relevant part of the typed string from file names or folder names in the current folder. The relevant part is usually the last space-free part, but use of quotation marks changes that. Generally considers both files and folders for completion, but cd command only considers folders. Up and down arrow keys: Enters commands from the command history, one at a time. Escape: Erases the current command line being typed. F1: Types the characters from the single previously entered command from the command history, one character at a time. Each subsequent press of F1 enters one more character. F2: Asks you to type a character, and enters the shortest prefix of the previous command from the command history that does not include the typed character. Thus, if the previous command was echo Hello world and you typed o, enters ech. F3: Enters the single previous command from the command history. Repeated pressing has no further effect. F4: Asks you to type a character, and erases the part of the currently typed string that starts at the current cursor location, continues to the right, and ends with the character you entered excluding that character. Thus, if you type echo Hello world, place the cursor at H using left arrow key, press F4 and then w, you get echo world. F5: Enters previous commands from the command history, one at a time. F6: Enters Control+Z character. F7: Opens a character-based popup window with the command history, and lets you use arrow key and enter to select a command. After you press enter in the popup, the command is immediately executed. F8: Given an already typed string, shows items from the command history that have that string as a prefix, one at a time. F9: Lets you enter the number of the command from the command history, and then executes the command. Alt + F7: Erases the command history. The above are also known as command prompt keyboard shortcuts. The availability of the above shortcuts does not seem to depend on running DOSKEY.

Perl one-liners

Some tasks can be conveniently achieved with Perl one-liners. Perl is a scripting language originating in the environment of another operating system. Since many Windows computing environments have Perl installed, Perl one-liners are a natural and compact extension of Windows batch scripting. Examples: echo "abcbbc"| perl -pe "s/a.*?c/ac/" Lets Perl act as sed, the utility that supports textual replacements specified using regular expressions. echo a b| perl -lane "print $F[1]" Lets Perl act as cut command, displaying the 2nd field or column of the line, in this case b. Use $F[2] to display 3rd field; indexing starts at zero. Native solution: FOR /f. perl -ne "print if /\x22hello\x22/" file.txt Acts as grep or FINDSTR, outputting the lines in file.txt that match the regular expression after if. Uses the powerful Perl regular expressions, more powerful than those of FINDSTR. perl -ne "$. <= 10 and print" MyFile.txt Lets Perl act as head -10 command, outputting the first 10 lines of the file. perl -e "sleep 5" Waits for 5 seconds. for /f%i in ('perl -MPOSIX -le "print strftime '%Y-%m-%d', localtime"') do @set isodate=%i Gets current date in the ISO format into isodate variable. perl -MWin32::Clipboard -e "print Win32::Clipboard->Get()" Outputs the text content of the clipboard. When stored to getclip.bat, yields a handy getclip command to complement CLIP command. On the web, Perl one-liners are often posted in the command-line conventions of another operating system, including the use of apostrophe (') to surround the arguments instead of Windows quotation marks. These need to be tweaked for Windows.

Limitations

There is no touch command familiar from other operating systems. The touch command would modify the last-modification timestamp of a file without changing its content. One workaround, with unclear reliability and applicability across various Windows versions, is this: copy /b file.txt+,,

Built-in commands

These commands are all built in to the command interpreter itself, and cannot be changed. Sometimes this is because they require access to internal command interpreter data structures, or modify properties of the command interpreter process itself.

Overview

CommandDescription
ASSOCAssociates an extension with a file type (FTYPE).
BREAKSets or clears extended CTRL+C checking.
CALLCalls one batch program from another.
CD, CHDIRDisplays or sets the current directory.
CHCPDisplays or sets the active code page number.
CLSClears the screen.
COLORSets the console foreground and background colors.
COPYCopies files.
DATEDisplays and sets the system date.
DEL, ERASEDeletes one or more files.
DIRDisplays a list of files and subdirectories in a directory.
ECHODisplays messages, or turns command echoing on or off.
ELSEPerforms conditional processing in batch programs when "IF" is not true.
ENDLOCALEnds localization of environment changes in a batch file.
EXITQuits the CMD.EXE program (command interpreter).
FORRuns a specified command for each file in a set of files.
FTYPESets the file type command.
IFPerforms conditional processing in batch programs.
MD, MKDIRCreates a directory.
MOVEMoves a file to a new location
PATHSets or modifies the PATH environment
PAUSECauses the command session to pause for user input.
POPDChanges to the drive and directory poped from the directory stack
PROMPTSets or modifies the string displayed when waiting for input.
PUSHDPushes the current directory onto the stack, and changes to the new directory.
RD / RMDIRRemoves the directory.
REMA comment command. Unlike double-colon (::), the command can be executed.
REN / RENAMERenames a file or directory
SETSets or displays shell environment variables
SETLOCALCreates a child-environment for the batch file.
SHIFTMoves the batch parameters forward.
STARTStarts a program with various options.
TIMEDisplays or sets the system clock
TITLEChanges the window title
TYPEPrints the content of a file to the console.
VERShows the command processor, operating system versions.
VERIFYVerifies that file copy has been done correctly.
VOLShows the label of the current volume.

ASSOC

Associates an extension with a file type (FTYPE), displays existing associations, or deletes an association. See also FTYPE. Examples: assoc Lists all associations, in the format "<file extension>=<file type>", as, for example, ".pl=Perl" or ".xls=Excel.Sheet.8". assoc | find ".doc" Lists all associations containing ".doc" substring.

BREAK

In Windows versions based on Windows NT, does nothing; kept for compatibility with MS DOS.

CALL

Calls one batch program from another, or calls a subprogram within a single batch program. Purpose: Calls another batch file and then returns to the current batch file to continue processing. Example To run the files STARTER.BAT, TESTER.BAT, and FINISH.BAT in sequence, enter the following three lines in your batch file: call starter call tester call finish CALL is the normal way to call another bat file within a .bat and return to the caller. However, all batch file processing will cease if the CALLed batch file has a fatal syntax error, or if the CALLed script terminates with EXIT without the /B option. You can guarantee control will return to the caller if you execute the 2nd script via the CMD command. cmd /c "calledFile.bat" But this has a limitation that the environment variables set by the called batch will not be preserved upon return. If you really need to preserve variables while using CMD, then you can have the "called" script write the variable changes to a temp file, and then have the caller read the temp file and re-establish the variables. call is necessary for .bat or .cmd files, else the control will not return to the caller. Start isn't the same as call, it creates a new cmd.exe instance, so it can run a called batch file asynchronosly

CD

Changes to a different directory, or displays the current directory. However, if a different drive letter is used, it does not switch to that different drive or volume. Examples: cd cd C:\Program Files cd \Program Files cd Documents cd%USERPROFILE% cd /d C:\Program Files Changes to the directory of the C: drive even if C: is not the current drive. C: & cd C:\Program Files. Changes to the directory of the C: drive even if C: is not the current drive. cd .. Changes to the parent directory. Does nothing if already in the root directory. cd ..\.. Changes to the parent directory two levels up. C: & cd C:\Windows\System32 & cd ..\..\Program Files Uses ".." to navigate through the directory three up and down No surrounding quotes are needed around paths with spaces.

CHDIR

A synonym of CD.

CLS

Clears the screen.

COLOR

Sets the console foreground and background colors. Examples: color f9 Use white background and blue foreground. color Restore the original color setting.

COPY

Copies files. See also MOVE. Examples: copy F:\File.txt Copies the file into the current directory, assuming the current directory is not F:\. copy "F:\My File.txt" As above; quotation marks are needed to surround a file with spaces. copy F:\*.txt Copies the files located at F:\ and ending in dot txt into the current directory, assuming the current directory is not F:\. copy F:\*.txt . Does the same as the above command. copy File.txt Issues an error message, as File.txt cannot be copied over itself. copy File1.txt File2.txt Copies File1.txt to File2.txt, overwriting File2.txt if confirmed by the user or if run from a batch script. copy File.txt "My Directory" Copies File.txt into "My Directory" directory, assuming "My Directory" exists. copy Dir1 Dir2 Copies all files directly located in directory Dir1 into Dir2, assuming Dir1 and Dir2 are directories. Does not copy files located in nested directories of Dir1. copy *.txt *.bak For each *.txt file in the current folder, makes a copy ending with "bak" rather than "txt".

DEL

Deletes files. Use with caution, especially in combination with wildcards. Only deletes files, not directories, for which see RD. For more, type "del /?". Examples: del File.txt del /s *.txt Deletes the files recursively including nested directories, but keeps the directories; mercilessly deletes all matching files without asking for confirmation. del /p /s *.txt As above, but asks for confirmation before every single file.

DIR

Lists the contents of a directory. Offers a range of options. Type "dir /?" for more help. Examples: dir Lists the files and folders in the current folder, excluding hidden files and system files; uses a different manner of listing if DIRCMD variable is non-empty and contains switches for dir. dir D: dir /b C:\Users dir /s Lists the contents of the directory and all subdirectories recursively. dir /s /b Lists the contents of the directory and all subdirectories recursively, one file per line, displaying complete path for each listed file or directory. dir *.txt Lists all files with .txt extension. dir /a Includes hidden files and system files in the listing. dir /ah Lists hidden files only. dir /ad Lists directories only. Other letters after /A include S, I, R, A and L. dir /ahd Lists hidden directories only. dir /a-d Lists files only, omitting directories. dir /a-d-h Lists non-hidden files only, omitting directories. dir /od Orders the files and folders by the date of last modification. Other letters after /O include N (by name), E (by extension), S (by size), and G (folders first) dir /o-s Orders the files by the size descending; the impact on folder order is unclear. dir /-c /o-s /a-d Lists files ordered by size descending, omitting the thousands separator via /-C, excluding folders. dir /s /b /od Lists the contents of the directory and all subdirectories recursively, ordering the files in each directory by the date of last modification. The ordering only happens per directory; the complete set of files so found is not ordered as a whole.

DATE

Displays or sets the date. The way the date is displayed depends on country settings. Date can also be displayed using "echo %DATE%". Getting date in the iso format, like "2000-01-28": That is nowhere easy, as the date format depends on country settings. If you can assume the format of "Mon 01/28/2000", the following will do: set isodate=%date:~10,4%-%date:~4,2%-%date:~7,2% If you have WMIC, the following is locale independent: for /f%i in ('wmic os get LocalDateTime') do @if%i lss a if%i gtr 0 set localdt=%i set isodate=%localdt:~0,4%-%localdt:~4,2%-%localdt:~6,2% To use the above in a batch, turn%i into%%i and remove @ from before if. If you have Perl installed: for /f%i in ('perl -MPOSIX -le "print strftime '%Y-%m-%d', localtime"') do @set isodate=%i

ECHO

Displays messages, or turns command echoing on or off. Examples: echo on @echo off echo Hello echo "hello" Displays the quotes too. echo %PATH% Displays the contents of PATH variable. echo Owner ^& son Uses caret (^) to escape ampersand (&), thereby enabling echoing ampersands. echo 1&echo 2&echo 3 Displays three strings, each followed by a newline. echo %random%>>MyRandomNumbers.txt While it seems to output random numbers to MyRandomNumbers.txt, it actually does not do so for numbers 0-9, since these, when placed before >>, indicate which channel is to be redirected. See also #Redirection. echo 2>>MyRandomNumbers.txt Instead of echoing 2, redirects standard error to the file. (echo 2)>>MyRandomNumbers.txt Echoes even a small number (in this case 2) and redirects the result. >>MyRandomNumbers.txt echo 2 Another way to echo even a small number and redirect the result. Displaying a string without a newline requires a trick: set <NUL /p=Output of a command: Displays "Output of a command:". The output of the next command will be displayed immediately after ":". set <NUL /p=Current time: & time /t Displays "Current time: " followed by the output of "time /t". (set <NUL /p=Current time: & time /t) >tmp.txt Like before, with redirecting the output of both commands to a file.

ELSE

An example: if exist file.txt ( echo The file exists. ) else ( echo The file does not exist. ) See also IF.

ENDLOCAL

Ends local set of environment variables started using SETLOCAL. Can be used to create subprograms: see Functions.

ERASE

A synonym of DEL.

EXIT

Exits the DOS console or, with /b, only the currently running batch or the currently executed subroutine. If used without /b in a batch file, causes the DOS console calling the batch to close. Examples: exit exit /b

FOR

Iterates over a series of values, executing a command. In the following examples, %i is to be used from the command line while %%i is to be used from a batch. Examples: for %%i in (1,2,3) do echo %%i In a batch, echoes 1, 2, and 3. In a batch, the command must use a double percent sign. The remaining examples are intended to be directly pasted into a command line, so they use a single percent sign and include "@" to prevent repetitive display. for %i in (1,2,3) do @echo %i From a command line, echoes 1, 2, and 3. The for command tries to interpret the items as file names and as patterns of file names containing wildcards. It does not complain if the items do not match existing file names, though. for %i in (1,2,a*d*c*e*t) do @echo %i Unless you happen to have a file matching the third pattern, echoes 1 and 2, discarding the third item. for %i in (1 2,3;4) do @echo %i Echoes 1, 2, 3, and 4. Yes, a mixture of item separators is used. for %i in (*.txt) do @echo %i Echoes file names of files located in the current folder and having the .txt extension. for %i in ("C:\Windows\system32\*.exe") do @echo %i Echoes file names matching the pattern. for /r%i in (*.txt) do @echo %i Echoes file names with full paths, of files having the extension .txt located anywhere in the current folder including nested folders. for /d%i in (*) do @echo %i Echoes the names of all folders in the current folder. for /r /d%i in (*) do @echo %i Echoes the names including full paths of all folders in the current folder, including nested folders. for /r%i in (*) do @if%~zi geq 1000000 echo %~zi%i For each file in the current folder and its subfolders that has the size greater than or equal to 1,000,000 bytes, outputs the file size in bytes and the full path of the file. For the syntax in%~zi, see #Percent tilde. for /l%i in (1,1,10) do @echo %i Echoes the numbers from 1 to 10. for /f "tokens=*"%i in (list.txt) do @echo %i For each line in a file, echoes the line. for /f "tokens=*"%i in (list1.txt list2.txt) do @echo %i For each line in the files, echoes the line. for /f "tokens=*"%i in (*.txt) do @echo %i Does nothing. Does not accept wildcards to match file names. for /f "tokens=1-3 delims=:"%a in ("First:Second::Third") do @echo %c-%b-%a Parses a string into tokens delimited by ":". The quotation marks indicate the string is not a file name. The second and third tokens are stored in%b and%c even though%b and%c are not expressly mentioned in the part of the command before "do". The two consecutive colons are treated as one separator;%c is not "" but rather "Third". Does some of the job of the cut command from other operating systems. for /f "tokens=1-3* delims=:"%a in ("First:Second::Third:Fourth:Fifth") do @echo %c-%b-%a:%d As above, just that the 4th and 5th items get captured in%d as "Fourth:Fifth", including the separator. for /f "tokens=1-3* delims=:,"%a in ("First,Second,:Third:Fourth:Fifth") do @echo %c-%b-%a:%d Multiple delimiters are possible. for /f "tokens=1-3"%a in ("First Second Third,item") do @echo %c-%b-%a The default delimiters are space and tab. Thus, they differ from the separators used to separate arguments passed to a batch. for /f "tokens=*"%i in ('cd') do @echo %i For each line of the result of a command, echoes the line. for /f "tokens=*"%i in ('dir /b /a-d-h') do @echo %~nxai For each non-hidden file in the current folder, displays the file attributes followed by the file name. In the string "%~nxai", uses the syntax described at #Percent tilde. for /f "usebackq tokens=*"%i in (`dir /b /a-d-h`) do @echo %~nxai As above, but using the backquote character (`) around the command to be executed. for /f "tokens=*"%i in ('tasklist ^| sort ^& echo End') do @echo %i Pipes and ampersands in the command to be executed must be escaped using caret (^). (for %i in (1,2,3) do @echo %i) > anyoldtemp.txt To redirect the entire result of a for loop, place the entire loop inside brackets before redirecting. Otherwise, the redirection will tie to the body of the loop, so each new iteration of the body of the loop will override the results of the previous iterations. for %i in (1,2,3) do @echo %i > anyoldtemp.txt An example related to the one above. It shows the consequence of failing to put the loop inside brackets. Continue: To jump to the next iteration of the loop and thus emulate the continue statement known from many languages, you can use goto provided you put the loop body in a subroutine, as shown in the following: for %%i in (a b c) do call :for_body %%i exit /b :for_body echo 1 %1 goto :cont echo 2 %1 :cont exit /b If you use goto directly inside the for loop, the use of goto breaks the loop bookkeeping. The following fails: for %%i in (a b c) do ( echo 1 %%i goto :cont echo 2 %%i :cont echo 3 %%i )

FTYPE

Displays or sets the command to be executed for a file type. See also ASSOC. Examples: ftype Lists all associations of commands to be executed with file types, as, for example, 'Perl="C:\Perl\bin\perl.exe" "%1"%*' ftype | find "Excel.Sheet" Lists only associations whose display line contains "Excel.Sheet"

GOTO

Goes to a label. An example: goto :mylabel echo Hello 1 REM Hello 1 never gets printed. :mylabel echo Hello 2 goto :eof echo Hello 3 REM Hello 3 never gets printed. Eof is a virtual label standing for the end of file. Goto within the body of a for loop makes cmd forget about the loop, even if the label is within the same loop body.

IF

Conditionally executes a command. Documentation is available by entering IF /? to CMD prompt. Available elementary tests: exist <filename> <string>==<string> <expression1> equ <expression2> -- equals <expression1> neq <expression2> -- not equal <expression1> lss <expression2> -- less than <expression1> leq <expression2> -- less than or equal <expression1> gtr <expression2> -- greater then <expression1> geq <expression2> -- greater than or equal defined <variable> errorlevel <number> cmdextversion <number> To each elementary test, "not" can be applied. Apparently there are no operators like AND, OR, etc. to combine elementary tests. The /I switch makes the == and equ comparisons ignore case. An example: if not exist %targetpath% ( echo Target path not found. exit /b ) Examples: if not 1 equ 0 echo Not equal if 1 equ 0 echo A & echo B Does nothing; both echo commands are subject to the condition. if not 1 equ 0 goto:mylabel if not a geq b echo Not greater if b geq a echo Greater if b geq A echo Greater in a case-insensitive comparison if B geq a echo Greater in a case-insensitive comparison if 0 equ 00 echo Numerical equality if not 0==00 echo String inequality if 01 geq 1 echo Numerical comparison if not "01" geq "1" echo String comparison if 1 equ 0 (echo Equal) else echo Unequal Notice the brackets around the positive then-part to make it work. if not a==A echo Case-sensitive inequality if /i a==A echo Case-insensitive equality if /i==/i echo This does not work if "/i"=="/i" echo Equal, using quotation marks to prevent the literal meaning of /i

MD

Creates a new directory or directories. Has a synonym MKDIR; see also its antonym RD. Examples: md Dir Creates one directory in the current directory. md Dir1 Dir2 Creates two directories in the current directory. md "My Dir With Spaces" Creates a directory with a name containing spaces in the current directory.

MKDIR

A synonym for MD.

MKLINK

Makes a symbolic link or other type of link. Available since Windows Vista.

MOVE

Moves files or directories between directories, or renames them. See also REN. Examples: move File1.txt File2.txt Renames File1.txt to File2.txt, overwriting File2.txt if confirmed by the user or if run from a batch script. move File.txt Dir Moves File.txt file into Dir directory, assuming File.txt is a file and Dir is a directory; overwrites target file Dir\a.txt if conditions for overwriting are met. move Dir1 Dir2 Renames directory Dir1 to Dir2, assuming Dir1 is a directory and Dir2 does not exist. move Dir1 Dir2 Moves directory Dir1 into Dir2, resulting in existence of Dir2\Dir1, assuming both Dir1 and Dir2 are existing directories. move F:\File.txt Moves the file to the current directory. move F:\*.txt Moves the files located at F:\ and ending in dot txt into the current directory, assuming the current directory is not F:\.

PATH

Displays or sets the value of the PATH environment variable.

PAUSE

Prompts the user and waits for a line of input to be entered.

POPD

Changes to the drive and directory poped from the directory stack. The directory stack is filled using the PUSHD command.

PROMPT

Can be used to change or reset the cmd.exe prompt. It sets the value of the PROMPT environment variable. C:\>PROMPT MyPrompt$G MyPrompt>CD C:\ MyPrompt>PROMPT C:\> The PROMPT command is used to set the prompt to "MyPrompt>". The CD shows that the current directory path is "C:\". Using PROMPT without any parameters sets the prompt back to the directory path.

PUSHD

Pushes the current directory onto the directory stack, making it available for the POPD command to retrieve, and, if executed with an argument, changes to the directory stated as the argument.

RD

Removes directories. See also its synonym RMDIR and antonym MD. Per default, only empty directories can be removed. Also type "rd /?". Examples: rd Dir1 rd Dir1 Dir2 rd "My Dir With Spaces" rd /s Dir1 Removes the directory Dir1 including all the files and subdirectories in it, asking for confirmation once before proceeding with the removal. To delete files recursively in nested directories with a confirmation per file, use DEL with /s switch. rd /q /s Dir1 Like above, but without asking for confirmation.

REN

Renames files and directories. Examples: ren filewithtpyo.txt filewithtypo.txt ren *.cxx *.cpp

RENAME

This is a synonym of REN command.

REM

Used for remarks in batch files, preventing the content of the remark from being executed. An example: REM A remark that does not get executed echo Hello REM This remark gets displayed by echo echo Hello & REM This remark gets ignored as wished :: This sentence has been marked as a remark using double colon. REM is typically placed at the beginning of a line. If placed behind a command, it does not work, unless preceded by an ampersand, as shown in the example above. An alternative to REM is double colon.

RMDIR

This is a synonym of RD.

SET

Displays or sets environment variables. With /P switch, it asks the user for input, storing the result in the variable. With /A switch, it performs simple arithmetic calculations, storing the result in the variable. With string assignments, there must be no spaces before and after the equality sign; thus, "set name = Peter" does not work, while "set name=Peter" does. Examples: set Displays a list of environment variables set HOME Displays the values of the environment variables whose names start with "HOME" set MYNUMBER=56 set HOME=%HOME%;C:\Program Files\My Bin Folder set /P user_input=Enter an integer: set /A result = 4 * ( 6 / 3 ) Sets the result variable with the result of a calculation. See also #Calculation.

SETLOCAL

When used in a batch file, makes all further changes to environment variables local to the current batch file. When used outside of a batch file, does nothing. Can be ended using ENDLOCAL. Exiting a batch file automatically calls "end local". Can be used to create subprograms: see Functions. Furthermore, can be used to enable delayed expansion like this: "setlocal EnableDelayedExpansion". Delayed expansion consists in the names of variables enclosed in exclamation marks being replaced with their values only after the execution reaches the location of their use rather than at an earlier point. The following is an example of using delayed expansion in a script that prints the specified number of first lines of a file, providing some of the function of the command "head" known from other operating systems: @echo off call :myhead 2 File.txt exit /b :: Function myhead :: =============== :: %1 - lines count, %2 - file name :myhead setlocal EnableDelayedExpansion set counter=1 for /f "tokens=*" %%i in (%2) do ( echo %%i set /a counter=!counter!+1 if !counter! gtr %1 exit /b ) exit /b

SHIFT

Shifts the batch file arguments along, but does not affect%*. Thus, if%1=Hello 1,%2=Hello 2, and%3=Hello 3, then, after SHIFT,%1=Hello 2, and%2=Hello 3, but%* is "Hello 1" "Hello 2" "Hello 3".

START

Starts a program in new window, or opens a document. Uses an unclear algorithm to determine whether the first passed argument is a window title or a program to be executed; hypothesis: it uses the presence of quotes around the first argument as a hint that it is a window title. Examples: start notepad.exe & echo "Done." Starts notepad.exe, proceeding to the next command without waiting for finishing the started one. Keywords: asynchronous. start "notepad.exe" Launches a new console window with notepad.exe being its title, apparently an undesired outcome. start "" "C:\Program Files\Internet Explorer\iexplore.exe" Starts Internet Explorer. The empty "" passed as the first argument is the window title of a console that actually does not get opened, or at least not visibly so. start "C:\Program Files\Internet Explorer\iexplore.exe" Launches a new console window with "C:\Program Files\Internet Explorer\iexplore.exe" being its title, apparently an undesired outcome. start /wait notepad.exe & echo "Done." Starts notepad.exe, waiting for it to end before proceeding. start /low notepad.exe & echo "Done." As above, but starting the program with a low priority. start "" MyFile.xls Opens the document in the program assigned to open it. start Starts a new console (command-line window) in the same current folder. start . Opens the current folder in Windows Explorer. start .. Opens the parent folder in Windows Explorer. start "" "mailto:" Starts the application for writing a new email. start /b TODO:example-application-where-this-is-useful Starts the application without opening a new console window, redirecting the output to the console from which the start command was called.

TIME

Displays or sets the system time.

TITLE

Sets the title displayed in the console window.

TYPE

Prints the content of a file or files to the output. Examples: type filename.txt type a.txt b.txt type *.txt type NUL > tmp.txt Create an empty file (blank file).

VER

Shows the command processor or operating system version. C:\>VER Microsoft Windows XP [Version 5.1.2600] C:\> Some version strings: Microsoft Windows XP [Version 5.1.2600] Microsoft Windows [Version 6.0.6000] ... The word "version" appears localized.

VERIFY

Sets or clears the setting to verify whether COPY files etc. are written correctly.

VOL

Displays volume labels.

External commands

External commands available to Windows command interpreter are separate executable program files, supplied with the operating system by Microsoft, or bundled as standard with the third-party command interpreters. By replacing the program files, the meanings and functions of these commands can be changed. Many, but not all, external commands support the "/?" convention, causing them to write on-line usage information to their standard output and then to exit with a status code of 0.

ARP

Displays or changes items in the address resolution protocol cache, which maps IP addresses to physical addresses.

AT

Schedules a program to be run at a certain time. See also SCHTASKS.

ATTRIB

Displays or sets file attributes. With no arguments, it displays the attributes of all files in the current directory. With no attribute modification instructions, it displays the attributes of the files and directories that match the given search wildcard specifications. Similar to chmod of other operating systems. Modification instructions: To add an attribute, attach a '+' in front of its letter. To remove an attribute, attach a '-' in front of its letter Attributes: A - Archived H - Hidden S - System R - Read-only ...and possibly others. Examples: attrib Displays the attributes of all files in the current directory. attrib File.txt Displays the attributes of the file. attrib +r File.txt Adds the "Read-only" attribute to the file. attrib -a File.txt Removes the "Archived" attribute from the file. attrib -a +r File.txt Removes the "Archived" attribute and adds the "Read-only" attribute to the file. attrib +r *.txt Acts on a set of files. attrib /S +r *.txt Acts recursively in subdirectories. For more, type "attrib /?".

BCDEDIT

(Not in XP). Edits Boot Configuration Data (BCD) files. For more, type "bcdedit /?".

CACLS

Shows or changes discretionary access control lists (DACLs). See also ICACLS. For more, type "cacls /?".

CHCP

Displays or sets the active code page number. For more, type "chcp /?".

CHKDSK

Checks disks for disk problems, listing them and repairing them if wished. For more, type "chkdsk /?".

CHKNTFS

Shows or sets whether system checking should be run when the computer is started. The system checking is done using Autochk.exe. The "NTFS" part of the command name is misleading, since the command works not only with NTFS file system but also with FAT and FAT32 file systems. For more, type "chkntfs /?".

CHOICE

Lets the user choose one of multiple options by pressing a single key, and sets the error level as per the chosen option. Absent in Windows 2000 and Windows XP, it was reintroduced in Windows Vista, and has remained in Windows 7 and 8. Examples: choice /m "Do you agree" Presents the user with a yes/no question, setting the error level to 1 for yes and to 2 for no. If the user presses Control + C, the error level is 0. choice /c rgb /m "Which color do you prefer" Presents the user with a question, and indicates the letters for the user. Responds to user pressing r, g or b, setting the error level to 1, 2 or 3. An alternative is "set /p"; see SET.

CIPHER

Shows the encryption state, encrypts or decrypts folders on a NTFS volume.

CLIP

(Not in XP) Places the piped input to the clipboard. Examples: set | clip Places the listing of environment variables to the clipboard. clip < File1.txt Places the content of File1.txt to the clipboard.

CMD

Invokes another instance of Microsoft's CMD.

COMP

Compares files. See also FC.

COMPACT

Shows or changes the compression of files or folders on NTFS partitions.

CONVERT

Converts a volume from FAT16 or FAT32 file system to NTFS file system.

DEBUG

Allows to interactively examine file and memory contents in assembly language, hexadecimal or ASCII. Available in 32-bit Windows including Windows 7; the availability in 64-bit Windows is unclear. In modern Windows, useful as a quick hack to view hex content of a file. Keywords: hex dump, hexdump, hexadecimal dump, view hex, view hexadecimal, disassembler. Debug offers its own command line. Once on its command like, type "?" to find about debug commands. To view hex of a file, invoke debug.exe with the file name as a parameter, and then repeatedly type "d" followed by enter on the debug command line. Limitations: Being a DOS program, debug chokes on long file names. Use dir /x to find the 8.3 file name, and apply debug on that one. Debug cannot view larger files.

DISKCOMP

Compares the content of two floppies.

DISKCOPY

Copies the content of one floppy to another.

DISKPART

Shows and configures the properties of disk partitions.

DOSKEY

Above all, creates macros known from other operating systems as aliases. Moreover, provides functions related to command history, and enhanced command-line editing. Macros are an alternative to very short batch scripts. Macro-related examples: doskey da=dir /s /b Creates a single macro called "da" doskey np=notepad $1 Creates a single macro that passes its first argument to notepad. doskey /macrofile=doskeymacros.txt Loads macro definitions from a file. doskey /macros Lists all defined macros with their definitions. doskey /macros | find "da" Lists all macro definitions that contain "da" as a substring; see also FIND. Command history-related examples: doskey /history Lists the complete command history. doskey /history | find "dir" Lists each line of command history that contains "dir" as a substring doskey /listsize=100 Sets the size of command history to 100. To get help on doskey from command line, type "doskey /?".

DRIVERQUERY

Shows all installed device drivers and their properties.

EXPAND

Extracts files from compressed .cab cabinet files. See also #MAKECAB.

FC

Compares files, displaying the differences in their content in a peculiar way. Examples: fc File1.txt File2.txt >NUL && Echo Same || echo Different or error Detects difference using the error level of fc. The error level of zero means the files are the same; non-zero can mean the files differ but also that one of the files does not exist.

FIND

Searches for a string in files or input, outputting matching lines. Unlike FINDSTR, it cannot search folders recursively, cannot search for a regular expression, requires quotation marks around the sought string, and treats space literally rather than as a logical or. Examples: find "(object" *.txt dir /S /B | find "receipt" dir /S /B | find /I /V "receipt" Prints all non-matching lines in the output of the dir command, ignoring letter case. find /C "inlined" *.h Instead of outputting the matching lines, outputs their count. If more than one file is searched, outputs one count number per file preceded with a series of dashes followed by the file name; does not output the total number of matching lines in all files. find /C /V "" < file.txt Outputs the number of lines AKA line count in "file.txt". Does the job of "wc -l" of other operating systems. Works by treating "" as a string not found on the lines. The use of redirection prevents the file name from being output before the number of lines. type file.txt | find /C /V "" Like the above, with a different syntax. type *.txt 2>NUL | find /C /V "" Outputs the sum of line counts of the files ending in ".txt" in the current folder. The "2>NUL" is a redirection of standard error that removes the names of files followed by empty lines from the output. find "Schönheit" *.txt If run from a batch file saved in unicode UTF-8 encoding, searches for the search term "Schönheit" in UTF-8 encoded *.txt files. For this to work, the batch file must not contain the byte order mark written by Notepad when saving in UTF-8. Notepad++ is an example of a program that lets you write UTF-8 encoded plain text files without byte order mark. While this works with find command, it does not work with #FINDSTR. find "Copyright" C:\Windows\system32\a*.exe Works with binary files no less than text files. find from file C:\tp\lists.txt FIND "Application" C:\tp\lists.txt find isn't very powerful. It searches for one string only (even if it is two words): findstr has much more power, but you have to be careful how to use it: findstr "hello world" file.txt finds any line, that contains either hello or world or both of them. Finding both words in one line is possible with (find or findstr): find "word1" file.txt|find "word2" finding both words scattered over the file (find or findstr): find "word1" file.txt && find "word2" file.txt if %errorlevel%==0 echo file contains both words

FINDSTR

Searches for regular expressions or text strings in files. Does some of the job of "grep" command known from other operating systems, but is much more limited in the regular expressions it supports. Treats space in a regular expression as a disjunction AKA logical or unless prevented with /c option. Examples: findstr /s "[0-9][0-9].*[0-9][0-9]" *.h *.cpp Searches recursively all files whose name ends with dot h or dot cpp, printing only lines that contain two consecutive decimal digits followed by anything followed by two consecutive decimal digits. findstr "a.*b a.*c" File.txt Outputs all lines in File.txt that match any of the two regular expressions separated by the space. Thus, the effect is one of logical or on regular expressions. echo world | findstr "hello wo.ld" Does not match. Since the 1st item before the space does not look like a regex, findstr treats the whole search term as a plain search term. echo world | findstr /r "hello wo.ld" Matches. The use of /r forces regex treatment. findstr /r /c:"ID: *[0-9]*" File.txt Outputs all lines in File.txt that match the single regular expression containing a space. The use of /c prevents the space from being treated as a logical or. The use of /r switches the regular expression treatment on, which was disabled by default by the use of /c. To test this, try the following: echo ID: 12|findstr /r /c:"ID: *[0-9]*$" Matches. echo ID: 12|findstr /c:"ID: *[0-9]*$" Does not match, as the search string is not interpreted as a regular expression. echo ID: abc|findstr "ID: *[0-9]*$" Matches despite the output of echo failing to match the complete regular expression: the search is interpreted as one for lines matching "ID:" or "*[0-9]*$". findstr /ric:"id: *[0-9]*" File.txt Does the same as the previous example, but in a case-insensitive manner. While findstr enables this sort of accumulation of switches behind a single "/", this is not possible with any command. For instance, "dir /bs" does not work, while "dir /b /s" does. To test this, try the following: echo ID: 12|findstr /ric:"id: *[0-9]*$" echo ID: ab|findstr /ric:"id: *[0-9]*$" findstr /msric:"id: *[0-9]*" *.txt Like above, but recursively for all files per /s, displaying only matching files rather than matching lines per /m. echo hel lo | findstr /c:"hel lo" /c:world /c switch can be used multiple times to create logical or. echo \hello\ | findstr "\hello\" Does not match. Backslash before quotation marks and multiple other characters acts as an escape; thus, \" matches ". echo \hello\ | findstr "\\hello\\" Matches. Double backslash passed to findstr stands for a single backslash. echo \hello\ | findstr \hello\ Matches. None of the single backslashes passed to findstr is followed by a character on which the backslash acts as an escape. echo ^"hey | findstr \^"hey | more To search for a quote (quotation mark), you need to escape it two times: once for the shell using caret (^), and once for findstr using backslash (\). echo ^"hey | findstr ^"\^"hey there^" | more To search for a quote and have the search term enclosed in quotes as well, the enclosing quotes need to be escaped for the shell using caret (^). echo //comment line | findstr \// If forward slash (/) is the 1st character in the search term, it needs to be escaped with a backslash (\). The escaping is needed even if the search term is enclosed in quotes. findstr /f:FileList.txt def.*(): Search in the files stated in FileList.txt, one file per line. File names in FileList.txt can contain spaces and do not need to be surrounded with quotation marks for this to work. findstr /g:SearchTermsFile.txt *.txt Search for the search terms found in SearchTermsFile.txt, one search term per line. A space does not serve to separate two search terms; rather, each line is a complete search term. A line is matched if at least one of the search terms matches. If the first search term looks like a regex, the search will be a regex one, but if it looks like a plain search term, the whole search will be a plain one even if 2nd or later search terms look like regex. findstr /xlg:File1.txt File2.txt Outputs set intersection: lines present in both files. findstr /xlvg:File2.txt File1.txt Outputs set difference: File1.txt - File2.txt. findstr /m Microsoft C:\Windows\system32\*.com Works with binary files no less than text files. Limitations of the regular expressions of "findstr", as compared to "grep": No support of groups -- "\(", "\)". No support of greedy iterators -- "*?". No support of "zero or one of the previous" -- "?". And more. Other limitations: There is a variety of limitations and strange behaviors as documented at What are the undocumented features and limitations of the Windows FINDSTR command?. Also consider typing "findstr /?".

FORFILES

Finds files by their modification date and file name pattern, and executes a command for each found file. Is very limited, especially compared to the find command of other operating systems. Available since Windows Vista. For more, type "forfiles /?". Examples: forfiles /s /d 06/10/2015 /c "cmd /c echo @fdate @path" For each file in the current folder and its subfolders modified on 10 June 2015 or later, outputs the file modification date and full file path. The date format after /d is locale specific. Thus, allows to find most recently modified files. Keywords: most recently changed files. forfiles /m *.txt /s /d 06/10/2015 /c "cmd /c echo @fdate @path" As above, but only for files ending in .txt.

FORMAT

Formats a disk to use Windows-supported file system such as FAT, FAT32 or NTFS, thereby overwriting the previous content of the disk. To be used with great caution.

FSUTIL

A powerful tool performing actions related to FAT and NTFS file systems, to be ideally only used by powerusers with an extensive knowledge of the operating systems. Fsutil: behavior Fsutil: dirty Fsutil: file Fsutil: fsinfo Fsutil: hardlink Fsutil: objectid Fsutil: quota Fsutil: reparsepoint Fsutil: sparse Fsutil: usn Fsutil: volume

GPRESULT

Displays group policy settings and more for a user or a computer.

GRAFTABL

Enables the display of an extended character set in graphics mode. Fore more, type "graftabl /?".

HELP

Shows command help. Examples: help Shows the list of Windows-supplied commands. help copy Shows the help for COPY command, also available by typing "copy /?".

ICACLS

(Not in XP) Shows or changes discretionary access control lists (DACLs) of files or folders. See also CACLS. Fore more, type "icacls /?".

IPCONFIG

Displays Windows IP Configuration. Shows configuration by connection and the name of that connection (i.e. Ethernet adapter Local Area Connection) Below that the specific info pertaining to that connection is displayed such as DNS suffix and ip address and subnet mask.

LABEL

Adds, sets or removes a disk label.

MAKECAB

Places files into compressed .cab cabinet file. See also #EXPAND.

MODE

A multi-purpose command to display device status, configure ports and devices, and more.

MORE

Displays the contents of a file or files, one screen at a time. When redirected to a file, performs some conversions, also depending on the used switches. Examples: more Test.txt more *.txt grep -i sought.*string Source.txt | more /p >Out.txt Taking the output of a non-Windows grep command that produces line breaks consisting solely of LF character without CR character, converts LF line breaks to CR-LF line breaks. CR-LF newlines are also known as DOS line breaks, Windows line breaks, DOS newlines, Windows newlines, and CR/LF line endings,as opposed to LF line breaks used by some other operating systems. In some setups, seems to output gibberish if the input contains LF line breaks and tab characters at the same time. In some setups, for the conversion, /p may be unneeded. Thus, "more" would convert the line breaks even without /p. more /t4 Source.txt >Target.txt Converts tab characters to 4 spaces. In some setups, tab conversion takes place automatically, even without the /t switch. If so, it is per default to 8 spaces. Switch /e: The online documentation for "more" in Windows XP and Windows Vista does not mention the switch. The switch /e is mentioned in "more /?" at least in Windows XP and Windows Vista. Per "more /?", the switch is supposed to enable extended features listed at the end of "more /?" help such as showing the current row on pressing "=". However, in Windows XP and Windows Vista, that seems to be enabled by default even without /e. Hypothesis: In Windows XP and Windows Vista, /e does not do anything; it is present for compatibility reasons.

NET

Provides various network services, depending on the command used. Available variants per command: net accounts net computer net config net continue net file net group net help net helpmsg net localgroup net name net pause net print net send net session net share net start net statistics net stop net time net use net user net view

OPENFILES

Performs actions pertaining to open files, especially those opened by other users over the network. The actions involve querying, displaying, and disconnecting. For more, type "openfiles /?".

PING

Syntax: PING /? PING address PING hostname Send ICMP/IP "echo" packets over the network to the designated address (or the first IP address that the designated hostname maps to via name lookup) and print all responses received.

RECOVER

Recovers as much information as it can from damaged files on a defective disk.

REPLACE

Replaces files in the destination folder with same-named files in the source folder.

ROBOCOPY

(Not in XP) Copies files and folders. See also XCOPY and COPY.

RUNDLL32

Runs a function available from a DLL. The available DLLs and their functions differ among Windows versions. Examples: rundll32 sysdm.cpl,EditEnvironmentVariables In some Windows versions, opens the dialog for editing environment variables.

SCHTASKS

Schedules a program to be run at a certain time, more powerful than AT.

SETX

Like SET, but affecting the whole machine rather than the current console or process. Not available in Windows XP; available in Windows Vista and later.

SHUTDOWN

Shuts down a computer, or logs off the current user.

SORT

Sorts alphabetically, from A to Z or Z to A. Cannot sort numerically: if the input contains one integer per line, "12" comes before "9". Examples: sort File.txt Outputs the sorted content of File.txt. sort /r File.txt Sorts in reverse order, Z to A. dir /b | sort

SUBST

Assigns a drive letter to a local folder, displays current assignments, or removes an assignment. Examples: subst p: . Assigns p: to the current folder. subst Shows all assignments previously made using subst. subst /d p: Removes p: assignment.

SYSTEMINFO

Shows configuration of a computer and its operating system.

TASKKILL, Closing application via .bat file

Ends one or more tasks. Examples: taskkill /im AcroRd32.exe Ends all process with the name "AcroRd32.exe"; thus, ends all open instances of Acrobat Reader. The name can be found using tasklist. taskkill /f /im AcroRd32.exe As above, but forced. Succeeds in ending some processes that do not get ended without /f. taskkill /IM asperascp.exe /F taskkill /f "USERNAME eq NT AUTHORITY\SYSTEM" /im notepad.exe tasklist | find "notepad" taskkill /PID 5792 Ends the process AKA task with process ID (PID) of 5792; the assumption is you have found the PID using tasklist. TASKLIST.exe TaskList displays all running applications and services with their Process ID (PID) This can be run on either a local or a remote computer. Tasklist options Options: /s computer Name or IP address of a remote computer. Don't use backslashes. Default = local computer. /u domain\user [/p password]] Run under a different account. /P [password] The password for the given user context. Prompts for input if omitted. /M [module] List all tasks currently using the given exe/dll name. If the module name is not specified all loaded modules are displayed. /svc List information for each process without truncation. Valid when /fo=TABLE. Cannot be used with /m or /v /APPS Display Store Apps and their associated processes. (Windows 8.1+) /V Verbose task information. /FO {TABLE|LIST|CSV}] Output format, the default is TABLE. /NH No Headers in the output (does not apply to LIST output) /FI FilterName [/FI FilterName2 [ ... ]] Apply one of the Filters below: ImageName eq, ne Image Name String PID eq, ne, gt, lt, ge, le Process ID, A Positive integer. Session eq, ne, gt, lt, ge, le Any valid session number. SessionName eq, ne String Status eq, ne RUNNING | NOT RESPONDING | UNKNOWN CPUTime eq, ne, gt, lt, ge, le Time hh:mm:ss MemUsage eq, ne, gt, lt, ge, le Memory usage in KB, specify a valid integer. Username eq, ne User name ([Domain\]User). Services eq, ne Service Name String Windowtitle eq, ne Window Title String Modules eq, ne DLL Name String Image Name is the name of the process or the executable file running the process, often svchost.exe Filters must be surrounded with double quotation marks, if a filter string itself includes a double quotation mark, this must be escaped with a backslash \" one exception to this is a double quote at the end, which can be matched using a wildcard: * if a filter string includes a backslash, that can be escaped with a double backslash \\ Home editions of Windows do not have TASKLIST, use QPROCESS instead. Examples List the services running under each process: C:\> tasklist.exe /svc List the services running under each SvcHost process: C:\> tasklist /FI "imagename eq svchost.exe" /svc tasklist | find "chrome" List the services/applications with a status of 'running': C:\> tasklist /v /fi "STATUS eq running" List the applications with an ImageName that starts with "C" - notice that a wildcard can only be used at the end of the string: C:\> tasklist /FI "IMAGENAME eq c*" List the applications running on a remote machine and sort the list: C:\> tasklist /s workstation64 | sort List the applications running under a specific user account: C:\> tasklist /v /fi "username eq SERVICE_ACCT05" To display the full path of a process in PowerShell: Get-Process -id 11832 | Select name, path Name Path ---- ---- notepad C:\Windows\system32\notepad.exe “Here's to the success of our impossible task!” ~ Soviet dissidents, 1975 Related commands Query Process - Display processes (TS/Remote Desktop). PsList - List detailed information about processes. TLIST - Task list with full path. MSINFO32 - Windows System Information. NETSTAT - Display current TCP/IP network connections. WMIC /OUTPUT:C:\demo\procs.txt PROCESS get Caption,Commandline,Processid Equivalent PowerShell: Get-Process - Get a list of processes on a machine (ps/gps). Equivalent bash command (Linux): ps - Process status, information about processes running in memory.

TASKLIST

Lists all tasks, including task name and process id (PID). Examples: tasklist | sort tasklist | find "notepad" tasklist | find "AcroRd" tasklist | find "chrome.exe" Displays the number of tasks named "chrome.exe", belonging to Google Chrome browser. tasklist | find /C "chrome.exe"

TIMEOUT

Waits a specified number of seconds, displaying the number of remaining seconds as time passes, allowing the user to interrupt the waiting by pressing a key. Also known as delay or sleep. Available in Windows Vista and later. Examples: timeout /t 5 Waits for five seconds, allowing the user to cancel the waiting by pressing a key. timeout /t 5 /nobreak Waits for five seconds, ignoring user input other than Control + C. timeout /t 5 /nobreak >nul As above, but with no output. Workaround in Windows XP: ping -n 6 127.0.0.1 >nul Waits for five seconds; the number after -n is the number of seconds to wait plus 1. Perl-based workaround in Windows XP, requiring Perl installed: perl -e "sleep 5" Waits for 5 seconds.

TREE

Displays a tree of all subdirectories of the current directory to any level of recursion or depth. If used with /F switch, displays not only subdirectories but also files. Examples: tree tree /f Includes files in the listing, in addition to directories. tree /f /a As above, but uses 7-bit ASCII characters including "+", "-" and \" to draw the tree. A snippet of a tree using 8-bit ASCII characters: ├───winevt │ ├───Logs │ └───TraceFormat ├───winrm A snippet of a tree using 7-bit ASCII characters: +---winevt | +---Logs | \---TraceFormat +---winrm

WHERE

Outputs one or more locations of a file or a file name pattern, where the file or pattern does not need to state the extension if it listed in PATHEXT, such as .exe. Searches in the current directory and in the PATH by default. Does some of the job of "which" command of some other operating systems, but is more flexible. Available on Windows 2003, Windows Vista, Windows 7, and later; not available on Windows XP. An alternative to be used with Windows XP is in the examples below. Does not find internal commands, as there are no dot exe files for them to match. Examples: where find Outputs the location of the find command, possibly "C:\Windows\System32\find.exe". The .exe extension does not need to be specified as long as it is listed in PATHEXT, which it is by default. If there are more find commands in the path, outputs paths to both. In some situations, it can output the following: C:\Windows\System32\find.exe C:\Program Files\GnuWin32\bin\find.exe for %i in (find.exe) do @echo %~$PATH:i Outputs the location of "find.exe" on Windows XP. The name has to include ".exe", unlike with the where command. where /r . Tasks* Searches for files whose name matches "Task*" recursively from the current folder. Similar to "dir /b /s Tasks*". The /r switch disables search in the folders in PATH. where *.bat Outputs all .bat files in the current directory and in the directories that are in PATH. Thus, outputs all .bat files that you can run without entering their full path. where ls*.bat As above, constraining also the beginning of the name of the .bat files. where ls* As above, but with no constraint on the extension. Finds lsdisks.bat, lsmice.pl, and lsmnts.py if in the current directory or in the path. where *.exe *.com | more Displays countless .exe and .com files in the path and in the current folder, including those in C:\Windows\System32. where $path:*.bat Outputs .bat files in the path but not those in the current folder unless the current folder is in PATH. Instead of path, another environment variable containing a list of directories can be used. where $windir:*.exe Outputs .exe files found in the folder stated in WINDIR environment variable. where $path:*.bat $windir:*.exe A combination is possible. Outputs all files matching either of the two queries. where /q *.bat && echo Found Suppresses both standard and error output, but sets the error level, enabling testing on it. The error level is set either way, with or without /q.

WMIC

Starts Windows Management Instrumentation Command-line (WMIC), or with arguments given, passes the arguments as commands to WMIC. Not in Windows XP Home. For more, type "wmic /?". Examples: wmic logicaldisk get caption,description Lists drives (disks) accessible under a drive letter, whether local hard drives, CD-ROM drives, removable flash drives, network drives or drives created using #SUBST.

XCOPY

Copies files and directories in a more advanced way than COPY, deprecated in Windows Vista and later. Type xcopy /? to learn more, including countless options. Examples: xcopy C:\Windows\system Copies all files, but not files in nested folders, from the source folder ("C:\Windows\system") to the current folder. xcopy /s /i C:\Windows\system C:\Windows-2\system Copies all files and folders to any nesting depth (via "/s") from the source folder ("C:\Windows\system") to "C:\Windows-2\system", creating "Windows-2\system" if it does not exist (via "/i"). xcopy /s /i /d:09-01-2014 C:\Windows\system C:\Windows-2\system As above, but copies only files changed on 1 September 2014 or later. Notice the use of the month-first convention even if you are on a non-US locale of Windows. xcopy /L /s /i /d:09-01-2014 C:\Windows\system C:\Windows-2\system As above, but in a test mode via /L (list-only, output-only, display-only). Thus, does not do any actual copying, merely lists what would be copied.

echo a newline in a batch file

echo hello echo, echo world echo hello & echo,world This means you could define & echo. as a constant for a newline \n. For printing just an empty line, you could use one of echo, echo; echo( echo/ echo+ echo= But the use of echo., echo\ or echo: should be avoided, as they can be really slow, depending of the location where the script will be executed, like a network drive.

editing environment variables

rundll32 sysdm.cpl,EditEnvironmentVariables

Doskey syntax

DOSKEY [/REINSTALL] [/LISTSIZE=size] [/MACROS[:ALL | :exename]] [/HISTORY] [/INSERT | /OVERSTRIKE] [/EXENAME=exename] [/MACROFILE=filename] [macroname=[text]]
/REINSTALLInstalls a new copy of Doskey.
/LISTSIZE=sizeSets the size of command history buffer.
/MACROSDisplays all Doskey macros.
/MACROS:ALLDisplays all Doskey macros for all executables which have Doskey macros.
/MACROS:exenameDisplays all Doskey macros for the given executable.
/HISTORYDisplays all commands stored in memory.
/INSERTSpecifies that new text you type is inserted in the old text.
/OVERSTRIKESpecifies that new text overwrites old text.
/EXENAME=exenameSpecifies the executable.
/MACROFILE=filenameSpecifies a file of macros to install.
macronameSpecifies a name for a macro you create.
textSpecifies commands you want to record.
Option keys
UP,DOWNThe up and down arrows recall commands.
EscClears current command.
F7Displays command history.
Alt+F7Clears command history.
[chars]F8Searches for command beginning with [chars].
F9Selects a command by number.
Alt+F10Clears macro definitions.
The following are some special codes in Doskey macro definitions:
$TCommand separator. Allows multiple commands in a macro.
$1-$9Batch parameters. Equivalent to %1-%9 in batch programs.
$*Symbol replaced by everything following macro name on the command line.

Windows XP and earlier syntax

DOSKEY [/switch ...] [macroname=[text]]
/BUFSIZE:sizeSets the size of macro and command buffer.(default:512)
/ECHO:on|offEnables/disables echo of macro expansions.(default:on)
/FILE:fileSpecifies file containing a list of macros.
/HISTORYDisplays all commands stored in memory.
/INSERTInserts new characters into line when typing.
/KEYSIZE:sizeSets the size of keyboard type-ahead buffer.(default:15)
/LINE:sizeSets the maximum size of line edit buffer.(default:128)
/MACROSDisplays all Doskey macros.
/OVERSTRIKEOverwrites new characters onto the line when typing.(default)
/REINSTALLInstalls a new copy of Doskey.
macronameSpecifies a name for a macro you create.
textSpecifies commands you want to assign to the macro.
Option keys
UP,DOWNArrows recall commands.
EscClears current command.
F7Displays command history.
Alt+F7Clears command history.
[chars]F8Searches for command beginning with [chars].
F9Selects a command by number.
Alt+F10Clears macro definitions.
Below are special codes you can use in Doskey macro definitions.
$TCommand separator: allows multiple commands in a macro.
$1-$9Batch parameters: equivalent to %1-%9 in batch programs.
$*Symbol replaced by everything following macro name on the command line.

Doskey examples

doskey Starts doskey and allows you to press the up or down command to see history, or right or left to retype the previous command. doskey /history Show the history of commands run at the command prompt. Since doskey is loaded by default with recent versions of Windows, this command is a quick way to determine what commands were run on any open Windows command line window.

MS-DOS Batch file pause with enter key

pause command, example: dir pause echo Now about to end... pause

display time

@echo off @echo %time% @echo HOUR:%time:~0,2% @echo MINUTE:%time:~3,2% Now type: SET/? Usage: Checktime 15:05 (for example) @echo off set Scr="%temp%\TempVBS.vbs" ( echo if minutes(CDate("%1"^)^) ^> minutes(Now^) Then WScript.Quit 0 Else WScript.Quit 1 echo Function minutes(dDate^) echo minutes = Hour(dDate^) * 60 + Minute(dDate^) echo End Function) > %Scr% cscript //nologo %Scr% if %ErrorLevel%==0 (echo Current time is ^< %1) else (echo Current time is ^>= %1)

play video

@Echo off set "file2=res\FORTNITESKINS.mp4" set wmplayer="%ProgramFiles(x86)%\Windows Media Player\wmplayer.exe" /prefetch:1 %wmplayer% "%file2%" /fullscreen

Running vbscript from batch file

VBS synchronously run in the same window @echo off pushd %~dp0 cscript necdaily.vbs VBS to synchronously run in a new window, then @echo off pushd %~dp0 start /wait "" cmd /c cscript necdaily.vbs VBS to asynchronously run in the same window @echo off pushd %~dp0 start /b "" cscript necdaily.vbs VBS to asynchronously run in a new window @echo off pushd %~dp0 start "" cmd /c cscript necdaily.vbs

open a cmd window in a specific location

open a cmd window in a specific location In File Explorer, press and hold the Shift key, then right click or press and hold on a folder or drive that you want to open the command prompt at that location for, and click/tap on Open Command Prompt Here option.

Batch Script - Variables

There are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command.

Command Line Arguments

Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on. The following example shows a batch file which accepts 3 command line arguments and echo's them to the command line screen. echo off echo %1 echo %2 echo %3 If the above batch script is stored in a file called test.bat and we were to run the batch as Test.bat 1 2 3 Following is a screenshot of how this would look in the command prompt when the batch file is executed. The above command produces the following output. 1 2 3 If we were to run the batch as Example 1 2 3 4 The output would still remain the same as above. However, the fourth parameter would be ignored.

Set Command

The other way in which variables can be initialized is via the 'set' command. Following is the syntax of the set command.

Syntax

set /A variable-name=value where, variable-name is the name of the variable you want to set. value is the value which needs to be set against the variable. /A – This switch is used if the value needs to be numeric in nature. The following example shows a simple way the set command can be used.

Example

echo off set message=Hello World echo %message% In the above code snippet, a variable called message is defined and set with the value of "Hello World". To display the value of the variable, note that the variable needs to be enclosed in the % sign.

Output

The above command produces the following output. Hello World

Working with Numeric Values

In batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch. The following code shows a simple way in which numeric values can be set with the /A switch. echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c% We are first setting the value of 2 variables, a and b to 5 and 10 respectively. We are adding those values and storing in the variable c. Finally, we are displaying the value of the variable c. The output of the above program would be 15. All of the arithmetic operators work in batch files. The following example shows arithmetic operators can be used in batch files. echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c% SET /A c = %a% - %b% echo %c% SET /A c = %b% / %a% echo %c% SET /A c = %b% * %a% echo %c% The above command produces the following output. 15 -5 2 50

Local vs Global Variables

In any programming language, there is an option to mark variables as having some sort of scope, i.e. the section of code on which they can be accessed. Normally, variable having a global scope can be accessed anywhere from a program whereas local scoped variables have a defined boundary in which they can be accessed. DOS scripting also has a definition for locally and globally scoped variables. By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL, any variable assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of file (EOF) in your script. The following example shows the difference when local and global variables are set in the script.

Example

echo off set globalvar = 5 SETLOCAL set var = 13145 set /A var = %var% + 5 echo %var% echo %globalvar% ENDLOCAL Few key things to note about the above program. The 'globalvar' is defined with a global scope and is available throughout the entire script. The 'var' variable is defined in a local scope because it is enclosed between a 'SETLOCAL' and 'ENDLOCAL' block. Hence, this variable will be destroyed as soon the 'ENDLOCAL' statement is executed.

Output

The above command produces the following output. 13150 5 You will notice that the command echo %var% will not yield anything because after the ENDLOCAL statement, the 'var' variable will no longer exist.

Working with Environment Variables

If you have variables that would be used across batch files, then it is always preferable to use environment variables. Once the environment variable is defined, it can be accessed via the % sign. The following example shows how to see the JAVA_HOME defined on a system. The JAVA_HOME variable is a key component that is normally used by a wide variety of applications. echo off echo %JAVA_HOME% The output would show the JAVA_HOME directory which would depend from system to system. Following is an example of an output. C:\Atlassian\Bitbucket\4.0.1\jre

print one single line in a different color

print one single line in a different color Use ANSI Escape Sequences. Windows before 10 - no native support for ANSI colors on the console For Windows version below 10, the Windows command console doesn't support output coloring by default. You could install either Cmder, ConEmu, ANSICON or Mintty (used by default in GitBash and Cygwin) to add coloring support to your Windows command console. Windows 10 - Command Line Colors Starting from Windows 10 the Windows console support ANSI Escape Sequences and some colors by default. The feature shipped with the Threshold 2 Update in Nov 2015. MSDN Documentation Update (05-2019): The ColorTool enables you to change the color scheme of the console. It's part of the Microsoft Terminal project. Demo Batch Command The win10colors.cmd was written by Michele Locati: The text below is stripped of special characters and will not work. You must copy it from here.

load the a text file into a batch file variable

https://stackoverflow.com/questions/134001/how-can-i-load-the-contents-of-a-text-file-into-a-batch-file-variable/66714820#66714820 If your set command supports the /p switch, then you can pipe input that way. - Create a file called "SetFile.bat" that contains no carriage return at the end set FileContents= Then in batch file do something like this... @echo off copy SetFile.bat + %1 $tmp$.bat > nul call $tmp$.bat del $tmp$.bat %1 is the name of your input file and %FileContents% will contain the contents of the input file after the call. This will only work on a one line file though (i.e. a file containing no carriage returns). You could strip out/replace carriage returns from the file before calling the %tmp%.bat if needed. - or: for /f "delims=" %%i in (count.txt) do set c=%%i echo %c% pause - If your set command supports the /p switch, then you can pipe input that way. set /p VAR1=<test.txt set /? |find "/P" The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty. This has the added benefit of working for un-registered file types (which the accepted answer does not). - Use for, something along the lines of: set content= for /f "delims=" %%i in ('filename') do set content=%content% %%i Maybe you'll have to do setlocal enabledelayedexpansion and/or use !content! rather than %content%. The best batch-file-black-magic-reference: http://www.rsdn.ru/article/winshell/batanyca.xml. - set content= for /f "delims=" %%i in ('type text.txt') do set content=!content! %%i

batch files command line arguments

https://www.tutorialspoint.com/batch_script/batch_script_variables.htm Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on. The following example shows a batch file which accepts 3 command line arguments and echo's them to the command line screen. @echo off echo %1 echo %2 echo %3 If the above batch script is stored in a file called test.bat and we were to run the batch as Test.bat 1 2 3 The above command produces the following output. 1 2 3 use %* to mean "all". Set Command The other way in which variables can be initialized is via the 'set' command. Following is the syntax of the set command. Syntax set /A variable-name=value where, variable-name is the name of the variable you want to set. value is the value which needs to be set against the variable. /A – This switch is used if the value needs to be numeric in nature. The following example shows a simple way the set command can be used. Example @echo off set message=Hello World echo %message% In the above code snippet, a variable called message is defined and set with the value of "Hello World". To display the value of the variable, note that the variable needs to be enclosed in the % sign. Output The above command produces the following output. Hello World Working with Numeric Values In batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch. The following code shows a simple way in which numeric values can be set with the /A switch. @echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c% We are first setting the value of 2 variables, a and b to 5 and 10 respectively. We are adding those values and storing in the variable c. Finally, we are displaying the value of the variable c. The output of the above program would be 15. All of the arithmetic operators work in batch files. The following example shows arithmetic operators can be used in batch files. @echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c% SET /A c = %a% - %b% echo %c% SET /A c = %b% / %a% echo %c% SET /A c = %b% * %a% echo %c% The above command produces the following output. 15 -5 2 50 Local vs Global Variables In any programming language, there is an option to mark variables as having some sort of scope, i.e. the section of code on which they can be accessed. Normally, variable having a global scope can be accessed anywhere from a program whereas local scoped variables have a defined boundary in which they can be accessed. DOS scripting also has a definition for locally and globally scoped variables. By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL, any variable assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of file (EOF) in your script. The following example shows the difference when local and global variables are set in the script. Example @echo off set globalvar = 5 SETLOCAL set var = 13145 set /A var = %var% + 5 echo %var% echo %globalvar% ENDLOCAL Few key things to note about the above program. The 'globalvar' is defined with a global scope and is available throughout the entire script. The 'var' variable is defined in a local scope because it is enclosed between a 'SETLOCAL' and 'ENDLOCAL' block. Hence, this variable will be destroyed as soon the 'ENDLOCAL' statement is executed. Output The above command produces the following output. 13150 5 You will notice that the command echo %var% will not yield anything because after the ENDLOCAL statement, the 'var' variable will no longer exist. Working with Environment Variables If you have variables that would be used across batch files, then it is always preferable to use environment variables. Once the environment variable is defined, it can be accessed via the % sign. The following example shows how to see the JAVA_HOME defined on a system. The JAVA_HOME variable is a key component that is normally used by a wide variety of applications. @echo off echo %JAVA_HOME% The output would show the JAVA_HOME directory which would depend from system to system. Following is an example of an output. C:\Atlassian\Bitbucket\4.0.1\jre

command-prompt execute vbs

Open a command window cscript filename.vbs The output of the script appears in the command window. To execute VBScript.vbs as a Windows application Select Start, Run... from the Windows toolbar. select the script file.

stash the vbscript in a batch/vbscript file hybrid

Converter.bat ::' VBS/Batch Hybrid ::' --- Batch portion --------- rem^ &@echo off rem^ &call :'sub rem^ &exit /b :'sub rem^ &echo begin batch rem^ &cscript //nologo //e:vbscript "%~f0" rem^ &echo end batch rem^ &exit /b '----- VBS portion ----- Dim tester tester = "Convert data here" Msgbox tester

Shell command doesn't work with space in directory name

Space separated text should be double quoted. This works for R's shell command. shell('C:\\"Program Files"\\SomeApp\\bin\\Release\\SomeApp.exe') To avoid space in path, omit the path, use filename directly

If - Conditionally perform a command

syntax
Compare strings that contain Spaces by using "double quotes"
Test if a variable is empty
Test if a variable is NULL
Test the existence of files and folders
Parenthesis
Pipes
Chaining IF commands (AND).
If either condition is true (OR)
Test Numeric values
Wildcards
ERRORLEVEL
Examples

syntax

File syntax IF [NOT] EXIST filename command IF [NOT] EXIST filename (command) ELSE (command) String syntax IF [/I] [NOT] item1==item2 command IF [/I] [NOT] "item1" == "item2" command IF [/I] item1 compare-op item2 command IF [/I] item1 compare-op item2 (command) ELSE (command) Error Check Syntax IF [NOT] DEFINED variable command IF [NOT] ERRORLEVEL number command IF CMDEXTVERSION number command key item A text string or environment variable, for more complex comparisons, a variable can be modified using either Substring or Search syntax. command The command to perform. filename A file to test or a wildcard pattern. NOT Perform the command if the condition is false. == Perform the command if the two strings are equal. /I Do a case Insensitive string comparison. compare-op can be one of EQU : Equal NEQ : Not equal LSS : Less than < LEQ : Less than or Equal <= GTR : Greater than > GEQ : Greater than or equal >= This 3 digit syntax is necessary because the > and < symbols are recognised as redirection operators IF will only parse numbers when one of (EQU, NEQ, LSS, LEQ, GTR, GEQ) is used. The == comparison operator always results in a string comparison.

Compare strings that contain Spaces by using "double quotes"

The IF command can seem flaky if any spaces exist in the comparison strings. for example these commands all seem like they work: IF 'ab'=='a b' Echo OK IF [ab]==[a b] Echo OK But if you reverse the logic to see if they are not equal, the code will fail and thow an error: IF 'ab' NEQ 'a b' Echo OK IF [ab] NEQ [a b] Echo OK Similarly this will fail: IF 'a b'=='a b' Echo OK The problem with the above, is that single quotes have no special meaning to CMD, so when it reaches a space it assumes that's the end of the string. These versions using double quotes will all work: IF "ab"=="a b" Echo OK IF "ab" NEQ "a b" Echo OK IF NOT "ab" == "a b" So then you think, OK I'll just use double quotes. However there is one remaining gotcha, if the item you are comparing is a quoted filename, so it already contains double quotes, you have an escape sequence: IF "long filename" EQU "something" Echo OK That will break because the " acts as an escape. To prevent that from happening strip any quotes from the strings being compared. In addition to spaces, the above applies to all other delimiters [Comma],[Semicolon], [Equals], [Space] [Tab]. Either the delimiters must be individually escaped with a caret ^ or the whole string must be "quoted".

Test if a variable is empty

To test for the existence of a command line parameter - use empty brackets like this: IF [%1]==[] ECHO Value Missing or IF [%1] EQU [] ECHO Value Missing When comparing against a variable that may be empty, we include a pair of brackets [ ] so that if the variable does happen to be empty the IF command still has something to compare: IF [] EQU [] will return True. You can in fact use almost any character for this a '~' or curly brackets, { } or even the number 4, but square brackets tend to be chosen because they don't have any special meaning. When working with filenames/paths you should always surround them with quotes, if %_myvar% contains "C:\Some Path" then your comparison becomes IF ["C:\Some Path"] EQU [] if %_myvar% could contain empty quotes, " then your comparison should become IF [%_myvar%] EQU ["] if %_myvar% will never contain quotes, then you can use quotes in place of the brackets IF "%_myvar%" EQU " However with this pattern if %_myvar% does unexpectedly contain quotes, you will get IF "C:\Some Path" EQU " those doubled quotes, act as an escape and will break the comparison.

Test if a variable is NULL

In the case of a variable that might be NULL - a null variable will remove the variable definition altogether, so testing for a NULL becomes: IF NOT DEFINED _example ECHO Value Missing IF DEFINED will return true if the variable contains any value (even if the value is just a space). To test for the existence of a variable use SET VariableName, or IF DEFINED VariableName

Test the existence of files and folders

IF EXIST filename Will detect the existence of a file or a folder. The script empty.cmd will show if the folder is empty or not (this is not case sensitive).

Parenthesis

Parenthesis can be used to split commands across multiple lines. This enables writing more complex IF… ELSE… commands: IF EXIST filename.txt ( Echo deleting filename.txt Del filename.txt ) ELSE ( Echo The file was not found. ) When combining an ELSE statement with parentheses, always put the opening parenthesis on the same line as ELSE. ) ELSE ( This is because CMD does a rather primitive one-line-at-a-time parsing of the command. When using parentheses the CMD shell will expand [read] all the variables at the beginning of the code block and use those values even if the variables value has just been changed. Turning on DelayedExpansion will force the shell to read variables at the start of every line.

Pipes

When piping commands, the expression is evaluated from left to right, so IF SomeCondition Command1 | Command2 is equivalent to: (IF SomeCondition Command1 ) | Command2 The pipe is always created and Command2 is always run, regardless whether SomeCondition is TRUE or FALSE You can use brackets and conditionals around the command with this syntax: IF SomeCondition (Command1 | Command2) If the condition is met then Command1 will run, and its output will be piped to Command2. The IF command will interpret brackets around a condition as just another character to compare (like # or @) for example: IF (%_var1%==(demo Echo the variable _var1 contains the text demo Placing an IF command on the right hand side of a pipe is also possible but the CMD shell is buggy in this area and can swallow one of the delimiter characters causing unexpected results.

Chaining IF commands (AND).

The only logical operator directly supported by IF is NOT, so to perform an AND requires chaining multiple IF statements: IF SomeCondition ( IF SomeOtherCondition ( Command_if_both_are_true ) )

If either condition is true (OR)

This can be tested using a temporary variable: Set "_tempvar=" If SomeCondition Set "_tempvar=1" If SomeOtherCondition Set "_tempvar=1" if %_tempvar% EQU 1 Command_to_run_if_either_is_true

Test Numeric values

IF only parses numbers when one of the compare-op operators (EQU, NEQ, LSS, LEQ, GTR, GEQ) is used. The == comparison operator always results in a string comparison. This is an important difference because if you compare numbers as strings it can lead to unexpected results: "2" will be greater than "19" and "026" will be less than "10". Correct numeric comparison: IF 2 GEQ 15 echo "bigger" Using parentheses or quotes will force a string comparison: IF (2) GEQ (15) echo "bigger" IF "2" GEQ "15" echo "bigger" This behaviour is exactly opposite to the SET /a command where quotes are required. IF should work within the full range of 32 bit signed integer numbers (-2,147,483,648 through 2,147,483,647) C:\> if 2147483646 GEQ 2147483647 (Echo Larger) Else (Echo Smaller) Smaller ⇨ correct C:\> if 2147483647 GEQ 2147483648 (Echo Larger) Else (Echo Smaller) Larger ⇨ wrong due to overflow C:\> if -2147483649 GEQ -2147483648 (Echo Larger) Else (Echo Smaller) Larger ⇨ wrong due to overflow You can perform a string comparison on very long numbers, but this will only work as expected when the numbers are exactly the same length: C:\> if "2147483647" GEQ "2147483648" (Echo Larger) Else (Echo Smaller) Smaller ⇨ correct

Wildcards

Wildcards are not supported by IF, so %COMPUTERNAME%==SS6* will not match SS64 A workaround is to retrieve the substring and compare just those characters: SET _prefix=%COMPUTERNAME:~0,3% IF %_prefix%==SS6 GOTO they_matched

ERRORLEVEL

There are two different methods of checking an errorlevel, the first syntax ( IF ERRORLEVEL ... ) provides compatibility with ancient batch files from the days of Windows 95. The second method is to use the %ERRORLEVEL% variable available in Windows 2000 or newer. IF ERRORLEVEL n statements should be read as IF Errorlevel >= number i.e. IF ERRORLEVEL 0 will return TRUE whether the errorlevel is 0, 1 or 5 or 64 IF ERRORLEVEL 1 will return TRUE whether the errorlevel is 1 or 5 or 64 IF NOT ERRORLEVEL 1 means if ERRORLEVEL is less than 1 (Zero or negative). This is not very readable or user friendly and does not easily account for negative error numbers. Using the %ERRORLEVEL% variable is a more logical method of checking Errorlevels: IF %ERRORLEVEL% NEQ 0 Echo An error was found IF %ERRORLEVEL% EQU 0 Echo No error found IF %ERRORLEVEL% EQU 0 (Echo No error found) ELSE (Echo An error was found) IF %ERRORLEVEL% EQU 0 Echo No error found || Echo An error was found This allows you to trap errors that can be negative numbers, you can also test for specific errors: IF %ERRORLEVEL% EQU 64 ... To deliberately raise an ERRORLEVEL in a batch script use the EXIT /B command. It is possible (though not a good idea) to create a string variable called %ERRORLEVEL% (user variable) if present such a variable will override and prevent the system variable %ERRORLEVEL% from being read by commands such as ECHO and IF. If Command Extensions are disabled IF will only support direct comparisons: IF ==, IF EXIST, IF ERRORLEVEL also the system variable CMDEXTVERSION will be disabled. In early versions of Windows NT/XP comparisons made using == would include the spaces before and after the ==, so for backwards compatibility you will still see commands written as IF alpha==beta rather than IF alpha == beta IF does not, by itself, set or clear the Errorlevel.

Examples

IF EXIST C:\logs\*.log (Echo Log file exists) IF EXIST C:\logs\install.log (Echo Complete) ELSE (Echo failed) IF DEFINED _department ECHO Got the _department variable IF DEFINED _commission SET /A "_salary=%_salary% + %_commission%" IF CMDEXTVERSION 1 GOTO start_process IF %ERRORLEVEL% EQU 2 goto sub_problem2 IF is an internal command.

to filter a string in batch file

set "temp1=project_Name_-_sofeware_Name.txt" set "dummy=%temp1:_-_=" & set "temp2=%" echo %temp2% output: set "temp1=project_Name_-_sofeware_Name.txt" set "dummy=project_Name" & set "temp2=sofeware_Name.txt" echo sofeware_Name.txt sofeware_Name.txt

String replacement in batch file

use the following little trick: set word=table set str="jump over the chair" call set str=%%str:chair=%word%%% echo %str% The call there causes another layer of variable expansion, making it necessary to quote the original % signs but it all works out in the end. output: set word=table set str="jump over the chair" call set str=%str:chair=table% echo "jump over the table" "jump over the table"

Special Characters in Batch File

Supposing you want the string ^&AntiBatchfileString literally, this is the best set syntax, as most special characters (^ & ( ) < > | and also the standard delimiters , ; = SPACE TAB) lose their particular meaning as soon as ther are placed in between "", and the "" themselves do not become part of the variable value: set "pass=^&AntiBatchfileString" This works only as long as the command extensions are on, which is the Windows default anyway (type cmd /? and see the /E option). When expanding (reading) a variable like "%pass%" (with enclosing ""), special characters are still treated literally. However, as soon as you expand it like %pass% (no ""), they get back their special meaning. So you have the following options: Use set "pass=^^^&AntiBatchfileString", where ^^ escapes the literal ^ and ^& the literal & when reading like %pass%. Enable delayed expansion (see set /? about how it works and setlocal /? or cmd /? about how to enable it), where the variable value is expanded (read) at a point of time where parsing of special characters has already been completed. I prefer the latter approach, because no special escaping is necessary, and it can also deal with " appearing in the string value (even if unsymmetrically present).
By the way, " can also be escaped by ^", as long as this does not appear within unescaped "". Nevertheless, % signs cannot be escaped like ^% in a batch file, because percent expansion happens before escaping, but you need to double them like %% to get one literal one each, independent whether or not the string is in between "".
Note that on the console, %% does not work. Finally, literal ! are consumed by the delayed expansion feature when enabled, therefore you need to pay particular attention to those in case, by escaping them like ^!, or also by intelligently toggling delayed expansion (hence to enable it only when it is actually needed and to disable it otherwise, when a literal string is provided, like in a set command line, for instance, when expanding a standard variable like %pass% and when reading a for variable like %%I (batch file) or %I (console), for example). Of course this is also not the ultimate solution, because you need setlocal and endlocal to enable/disable delayed expansion, which are intended to localise environment changes, so any variable changes since the most recent setlocal command are lost as soon as endlocal is executed (there are some tricks for passing a variable value over the endlocal barrier though). If you want to use % as a string without escaping in a batch file: Like %20, you can use %%%20. git clone "https:// abc.com /D%%%220an" Escape Characters

Batch Script Tutorial

https://www.tutorialspoint.com/batch_script/index.htm

 Batch Script Tutorial

Batch Scripts are stored in simple text files containing lines with commands that get executed in sequence, one after the other. Scripting is a way by which one can alleviate this necessity by automating these command sequences in order to make one's life at the shell easier and more productive. This tutorial discusses the basic functionalities of Batch Script along with relevant examples for easy understanding.

 What is Batch Scripting?

Batch scripting is a powerful tool for automating tasks on Windows operating systems. By writing scripts in plain text files with a ".bat" or ".cmd" extension, you can execute multiple commands without manual intervention, saving time and reducing the risk of errors. Batch scripting consists of a series of commands to be executed by the command-line interpreter, stored in a plain text file (batch file). Developers can automate various tasks such as creating files, deleting files, renaming files, and much more on servers and local machines using batch files. It is especially useful for repetitive tasks, like setting up new projects or automating routine tasks.

 Why to Learn Batch Script?

Batch scripting enables you to automate repetitive tasks, from file management to system administration, saving valuable time and reducing the risk of human error. Automation is necessary in enterprise-level and financial technology companies, where data and processes are vast and complex.

 Features of Batch Script

Batch Script has the following features - User Input - Batch script can read user input for further processing. Decision-making Structures - It supports control structures such as if, if/else, and nested if statements. Also supports looping commands like for and while for better automation and scripting. Advanced Features - Batch scripting supports functions and arrays for more complex operations. String Operations - It include support for strings and string manipulation. Debugging - Batch scripts come with debugging capabilities to troubleshoot and fix errors.

 Who Should Learn Batch Script?

This tutorial has been prepared for beginners to understand the basic concepts of Batch Script. Whether you are new to scripting or looking to automate your daily tasks, this guide will help you get started. Anyone involved in system administration, software development, or IT operations can benefit from learning batch scripting. It is particularly useful for - System Administrators - Automate routine administrative tasks and manage servers efficiently. Software Developers - Streamline development workflows and automate testing. IT Support Specialists - Simplify support tasks and enhance troubleshooting processes. Automation Engineers - Design and implement automated solutions for complex processes.

 Prerequisites to Learn Batch Script

A reasonable knowledge of computer programming and concepts such as variables, commands, and syntax is desired. Familiarity with the Windows operating system and command prompt is also helpful. Understanding these basics will make it easier to follow along with the examples and concepts discussed in this tutorial.

 Batch Script Jobs and Opportunities

Knowledge of batch scripting can open up various career opportunities, including - Data Engineer Quality Engineer Application Developer IT Operations Engineer Teamcenter Developer By mastering batch scripting, you can enhance your skill set and increase your efficiency in performing repetitive tasks, making you a valuable asset in any technical role.

 Applications of Batch Script

Batch scripting is widely used in various applications, including - Automation - Automate routine tasks to save time and effort. System Maintenance - Perform regular system maintenance tasks such as cleanups, and updates. File Management - Efficiently manage files and directories by automating creation, deletion, and renaming tasks. Software Deployment - Simplify the deployment process for applications by automating installation and configuration steps. Data Processing - Automate data processing tasks such as data extraction, transformation, and loading.

 Frequently Asked Questions about Batch Script Tutorial

There are some very Frequently Asked Questions (FAQ) about Batch Script, this section tries to answer them briefly. What is batch scripting used for? Batch scripting is used to automate tasks by running multiple commands without manual involvement. What do I need to run batch scripts? To run a batch script, you need to follow the below steps - Open the command prompt (cmd.exe). Navigate to the directory where the .bat or .cmd file is stored. Type the name of the file and press Enter. What does batch scripting do? Batch scripting automates command sequences that are repetitive in nature. It saves time and reduces the potential for human error by executing predefined commands automatically. Can you run batch files on OS other than Windows? Batch files are specific to Windows. However, Mac, Linux, and other UNIX-like systems have similar scripting capabilities using shell scripting (e.g., Bash). Is batch scripting still relevant today? Yes, batch scripting is still relevant. Although newer alternatives like PowerShell exist, batch scripts continue to be useful for certain tasks and work well on Windows 10. What can you do with batch script? With batch scripts, you can - Copy files from one location to another Delete files List the contents of a directory Create new directories Rename files and directories Compare files for differences Perform many other automated tasks Where do I run a batch script? To run a batch script - Open the command prompt (cmd.exe). Navigate to the directory where the .bat or .cmd file is stored. Type the name of the file and press Enter. How can I create a batch script? Batch scripts are usually created in Notepad. To create one - Open Notepad. Enter the commands you want to execute. Save the file with a .bat or .cmd extension. How do I delete a file in a Batch Script? Use the DEL command to delete a file - DEL filename You can use various switches with DEL for more control - DEL [/P] [/F] [/S] [/Q] [/A[[:]attributes]] names How do I save a Batch Script? Save your script with a .bat or .cmd extension. Avoid spaces and common command names to prevent conflicts. How do I delay a batch script? Use the timeout command to pause execution for a specified number of seconds - timeout /t 10 >nul You can also use pause to wait for user input - pause How to check if a file exists in batch script? You can use IF EXIST to check for a file.

Batch Script - Overview

Some of the features of Batch Script are - Can read inputs from users so that it can be processed further. Has control structures such as for, if, while, switch for better automating and scripting. Supports advanced features such as Functions and Arrays. Supports regular expressions. Can include other programming codes such as Perl. Some of the common uses of Batch Script are - Setting up servers for different purposes. Automating housekeeping activities such as deleting unwanted files or log files. Automating the deployment of applications from one environment to another. Installing programs on various machines at once. Batch scripts are stored in simple text files containing lines with commands that get executed in sequence, one after the other. These files have the special extension BAT or CMD. Files of this type are recognized and executed through an interface (sometimes called a shell) provided by a system file called the command interpreter. On Windows systems, this interpreter is known as cmd.exe. Running a batch file is a simple matter of just clicking on it. Batch files can also be run in a command prompt or the Start-Run line. In such case, the full path name must be used unless the file's path is in the path environment. Following is a simple example of a Batch Script. This Batch Script when run deletes all files in the current directory. :: Deletes All files in the Current Directory With Prompts and Warnings ::(Hidden, System, and Read-Only Files are Not Affected) :: @ECHO OFF DEL . DR

Batch Script - Environment

 Writing and Executing

Typically, to create a batch file, notepad is used. This is the simplest tool for creation of batch files. Next is the execution environment for the batch scripts. On Windows systems, this is done via the command prompt or cmd.exe. All batch files are run in this environment. Following are the different ways to launch cmd.exe - Method 1 - Go to C:\Windows\System32 and double click on the cmd file. Method 2 - Via the run command The following snapshot shows to find the command prompt(cmd.exe) on Windows server 2012. Once the cmd.exe is launched, you will be presented with the following screen. This will be your environment for executing your batch scripts.

 Environment Variables

In order to run batch files from the command prompt, you either need to go to the location to where the batch file is stored or alternatively you can enter the file location in the path environment variable. Thus assuming that the batch file is stored in the location C:\Application\bin, you would need to follow these instructions for the PATH variable inclusion.

Batch Script - Commands

S.NoCommands & Description
1VER This batch command shows the version of MS-DOS you are using.
2ASSOC This is a batch command that associates an extension with a file type (FTYPE), displays existing associations, or deletes an association.
3CD This batch command helps in making changes to a different directory, or displays the current directory.
4CLS This batch command clears the screen.
5COPY This batch command is used for copying files from one location to the other.
6DEL This batch command deletes files and not directories.
7DIR This batch command lists the contents of a directory.
8DATE This batch command help to find the system date.
9ECHO This batch command displays messages, or turns command echoing on or off.
10EXIT This batch command exits the DOS console.
11MD This batch command creates a new directory in the current location.
12MOVE This batch command moves files or directories between directories.
13PATH This batch command displays or sets the path variable.
14PAUSE This batch command prompts the user and waits for a line of input to be entered.
15PROMPT This batch command can be used to change or reset the cmd.exe prompt.
16RD This batch command removes directories, but the directories need to be empty before they can be removed.
17REN Renames files and directories
18REM This batch command is used for remarks in batch files, preventing the content of the remark from being executed.
19START This batch command starts a program in new window, or opens a document.
20TIME This batch command sets or displays the time.
21TYPE This batch command prints the content of a file or files to the output.
22VOL This batch command displays the volume labels.
23ATTRIB Displays or sets the attributes of the files in the curret directory
24CHKDSK This batch command checks the disk for any problems.
25CHOICE This batch command provides a list of options to the user.
26CMD This batch command invokes another instance of command prompt.
27COMP This batch command compares 2 files based on the file size.
28CONVERT This batch command converts a volume from FAT16 or FAT32 file system to NTFS file system.
29DRIVERQUERY This batch command shows all installed device drivers and their properties.
30EXPAND This batch command extracts files from compressed .cab cabinet files.
31FIND This batch command searches for a string in files or input, outputting matching lines.
32FORMAT This batch command formats a disk to use Windows-supported file system such as FAT, FAT32 or NTFS, thereby overwriting the previous content of the disk.
33HELP This batch command shows the list of Windows-supplied commands.
34IPCONFIG This batch command displays Windows IP Configuration. Shows configuration by connection and the name of that connection.
35LABEL This batch command adds, sets or removes a disk label.
36MORE This batch command displays the contents of a file or files, one screen at a time.
37NET Provides various network services, depending on the command used.
38PING This batch command sends ICMP/IP "echo" packets over the network to the designated address.
39SHUTDOWN This batch command shuts down a computer, or logs off the current user.
40SORT This batch command takes the input from a source file and sorts its contents alphabetically, from A to Z or Z to A. It prints the output on the console.
41SUBST This batch command assigns a drive letter to a local folder, displays current assignments, or removes an assignment.
42SYSTEMINFO This batch command shows configuration of a computer and its operating system.
43TASKKILL This batch command ends one or more tasks.
44TASKLIST This batch command lists tasks, including task name and process id (PID).
45XCOPY This batch command copies files and directories in a more advanced way.
46TREE This batch command displays a tree of all subdirectories of the current directory to any level of recursion or depth.
47FC This batch command lists the actual differences between two files.
48DISKPART This batch command shows and configures the properties of disk partitions.
49TITLE This batch command sets the title displayed in the console window.
50SET Displays the list of environment variables on the current system.

Batch Script - Files

 Creating Batch Files

Batch files are normally created in notepad. Hence the simplest way is to open notepad and enter the commands required for the script. For this exercise, open notepad and enter the following statements. :: Deletes All files in the Current Directory With Prompts and Warnings ::(Hidden, System, and Read-Only Files are Not Affected) :: @ECHO OFF DEL . DR

 Saving Batch Files

After your batch file is created, the next step is to save your batch file. Batch files have the extension of either .bat or .cmd. Some general rules to keep in mind when naming batch files - Try to avoid spaces when naming batch files, it sometime creates issues when they are called from other scripts. Don't name them after common batch files which are available in the system such as ping.cmd. The above screenshot shows how to save the batch file. When saving your batch file a few points to keep in mind. Remember to put the .bat or .cmd at the end of the file name. Choose the ※Save as type§ option as ※All Files§. Put the entire file name in quotes ※§.

 Executing Batch Files

Following are the steps to execute a batch file - Step 1 - Open the command prompt (cmd.exe). Step 2 - Go to the location where the .bat or .cmd file is stored. Step 3 - Write the name of the file as shown in the following image and press the Enter button to execute the batch file.

 Modifying Batch Files

Following are the steps for modifying an existing batch file. Step 1 - Open windows explorer. Step 2 - Go to the location where the .bat or .cmd file is stored. Step 3 - Right-click the file and choose the ※Edit§ option from the context menu. The file will open in Notepad for further editing.

Batch Script - Syntax

 ECHO Command

@echo off By default, a batch file will display its command as it runs. The purpose of this first command is to turn off this display. The command "echo off" turns off the display for the whole script, except for the "echo off" command itself. The "at" sign "@" in front makes the command apply to itself as well.

 Documentation

Very often batch files also contains lines that start with the "Rem" command. This is a way to enter comments and documentation. The computer ignores anything on a line following Rem. For batch files with increasing amount of complexity, this is often a good idea to have comments.

 First Batch Script Program

Let's construct our simple first batch script program. Open notepad and enter the following lines of code. Save the file as ※List.cmd§. The code does the following - Uses the echo off command to ensure that the commands are not shown when the code is executed. The Rem command is used to add a comment to say what exactly this batch file does. The dir command is used to take the contents of the location C:\Program Files. The '>' command is used to redirect the output to the file C:\lists.txt. Finally, the echo command is used to tell the user that the operation is completed. @echo off Rem This is for listing down all the files in the directory Program files dir "C:\Program Files" > C:\lists.txt echo "The program has completed" When the above command is executed, the names of the files in C:\Program Files will be sent to the file C:\Lists.txt and in the command prompt the message ※The program has completed§ will be displayed.

Batch Script - Variables

 Command Line Arguments

Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on. The following example shows a batch file which accepts 3 command line arguments and echo's them to the command line screen. @echo off echo %1 echo %2 echo %3 If the above batch script is stored in a file called test.bat and we were to run the batch as Test.bat 1 2 3 Following is a screenshot of how this would look in the command prompt when the batch file is executed. The above command produces the following output. 1 2 3 If we were to run the batch as Example 1 2 3 4 The output would still remain the same as above. However, the fourth parameter would be ignored.

 Set Command

The other way in which variables can be initialized is via the 'set' command. Following is the syntax of the set command.

Syntax

set /A variable-name=value where, variable-name is the name of the variable you want to set. value is the value which needs to be set against the variable. /A This switch is used if the value needs to be numeric in nature. The following example shows a simple way the set command can be used.

Example

@echo off set message=Hello World echo %message% In the above code snippet, a variable called message is defined and set with the value of "Hello World". To display the value of the variable, note that the variable needs to be enclosed in the % sign.

Output

The above command produces the following output. Hello World

 Working with Numeric Values

In batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch. The following code shows a simple way in which numeric values can be set with the /A switch. @echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c% We are first setting the value of 2 variables, a and b to 5 and 10 respectively. We are adding those values and storing in the variable c. Finally, we are displaying the value of the variable c. The output of the above program would be 15. All of the arithmetic operators work in batch files. The following example shows arithmetic operators can be used in batch files. @echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c% SET /A c = %a% - %b% echo %c% SET /A c = %b% / %a% echo %c% SET /A c = %b% * %a% echo %c% The above command produces the following output. 15 -5 2 50

 Local vs Global Variables

In any programming language, there is an option to mark variables as having some sort of scope, i.e. the section of code on which they can be accessed. Normally, variable having a global scope can be accessed anywhere from a program whereas local scoped variables have a defined boundary in which they can be accessed. DOS scripting also has a definition for locally and globally scoped variables. By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL, any variable assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of file (EOF) in your script. The following example shows the difference when local and global variables are set in the script.

Example

@echo off set globalvar = 5 SETLOCAL set var = 13145 set /A var = %var% + 5 echo %var% echo %globalvar% ENDLOCAL Few key things to note about the above program. The 'globalvar' is defined with a global scope and is available throughout the entire script. The 'var' variable is defined in a local scope because it is enclosed between a 'SETLOCAL' and 'ENDLOCAL' block. Hence, this variable will be destroyed as soon the 'ENDLOCAL' statement is executed.

Output

The above command produces the following output. 13150 5 You will notice that the command echo %var% will not yield anything because after the ENDLOCAL statement, the 'var' variable will no longer exist.

 Working with Environment Variables

If you have variables that would be used across batch files, then it is always preferable to use environment variables. Once the environment variable is defined, it can be accessed via the % sign. The following example shows how to see the JAVA_HOME defined on a system. The JAVA_HOME variable is a key component that is normally used by a wide variety of applications. @echo off echo %JAVA_HOME% The output would show the JAVA_HOME directory which would depend from system to system. Following is an example of an output. C:\Atlassian\Bitbucket\4.0.1\jre

Batch Script - Comments

For example, consider the following piece of code which has no form of comments. If any average person who has not developed the following script tries to understand the script, it would take a lot of time for that person to understand what the script actually does. ECHO OFF IF NOT "%OS%"=="Windows_NT" GOTO Syntax ECHO.%* | FIND "?" >NUL IF NOT ERRORLEVEL 1 GOTO Syntax IF NOT [%2]==[] GOTO Syntax SETLOCAL SET WSS= IF NOT [%1]==[] FOR /F "tokens = 1 delims = \ " %%A IN ('ECHO.%~1') DO SET WSS = %%A FOR /F "tokens = 1 delims = \ " %%a IN ('NET VIEW ^| FIND /I "\\%WSS%"') DO FOR /F "tokens = 1 delims = " %%A IN ('NBTSTAT -a %%a ^| FIND /I /V "%%a" ^| FIND "<03>"') DO ECHO.%%a %%A ENDLOCAL GOTO:EOF ECHO Display logged on users and their workstations. ECHO Usage: ACTUSR [ filter ] IF "%OS%"=="Windows_NT" ECHO Where: filter is the first part of the computer name^(s^) to be displayed

 Comments Using the Rem Statement

There are two ways to create comments in Batch Script; one is via the Rem command. Any text which follows the Rem statement will be treated as comments and will not be executed. Following is the general syntax of this statement.

Syntax

Rem Remarks where 'Remarks' is the comments which needs to be added. The following example shows a simple way the Rem command can be used.

Example

@echo off Rem This program just displays Hello World set message=Hello World echo %message%

Output

The above command produces the following output. You will notice that the line with the Rem statement will not be executed. Hello World

 Comments Using the :: Statement

The other way to create comments in Batch Script is via the :: command. Any text which follows the :: statement will be treated as comments and will not be executed. Following is the general syntax of this statement.

Syntax

:: Remarks where 'Remarks' is the comment which needs to be added. The following example shows the usage of the "::" command.

Example

@echo off :: This program just displays Hello World set message = Hello World echo %message%

Output

The above command produces the following output. You will notice that the line with the :: statement will not be executed. Hello World Note - If you have too many lines of Rem, it could slow down the code, because in the end each line of code in the batch file still needs to be executed. Let's look at the example of the large script we saw at the beginning of this topic and see how it looks when documentation is added to it. ::=============================================================== :: The below example is used to find computer and logged on users :: ::=============================================================== ECHO OFF :: Windows version check IF NOT "%OS%"=="Windows_NT" GOTO Syntax ECHO.%* | FIND "?" >NUL :: Command line parameter check IF NOT ERRORLEVEL 1 GOTO Syntax IF NOT [%2]==[] GOTO Syntax :: Keep variable local SETLOCAL :: Initialize variable SET WSS= :: Parse command line parameter IF NOT [%1]==[] FOR /F "tokens = 1 delims = \ " %%A IN ('ECHO.%~1') DO SET WSS = %%A :: Use NET VIEW and NBTSTAT to find computers and logged on users FOR /F "tokens = 1 delims = \ " %%a IN ('NET VIEW ^| FIND /I "\\%WSS%"') DO FOR /F "tokens = 1 delims = " %%A IN ('NBTSTAT -a %%a ^| FIND /I /V "%%a" ^| FIND "<03>"') DO ECHO.%%a %%A :: Done ENDLOCAL GOTO:EOF :Syntax ECHO Display logged on users and their workstations. ECHO Usage: ACTUSR [ filter ] IF "%OS%"=="Windows_NT" ECHO Where: filter is the first part of the computer name^(s^) to be displayed You can now see that the code has become more understandable to users who have not developed the code and hence is more maintainable.

Batch Script - Strings

S.NoStrings & Description
1Create String A string can be created in DOS in the following way.
2Empty String Empty String
3String Interpolation String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal.
4String Concatenation You can use the set operator to concatenate two strings or a string and a character, or two characters. Following is a simple example which shows how to use string concatenation.
5String length In DOS scripting, there is no length function defined for finding the length of a string. There are custom-defined functions which can be used for the same. Following is an example of a custom-defined function for seeing the length of a string.
6toInt A variable which has been set as string using the set variable can be converted to an integer using the /A switch which is using the set variable. The following example shows how this can be accomplished.
7Align Right This used to align text to the right, which is normally used to improve readability of number columns.
8Left String This is used to extract characters from the beginning of a string.
9Mid String This is used to extract a substring via the position of the characters in the string.
10Remove The string substitution feature can also be used to remove a substring from another string.
11Remove Both Ends This is used to remove the first and the last character of a string.
12Remove All Spaces This is used to remove all spaces in a string via substitution.
13Replace a String To replace a substring with another string use the string substitution feature.
14Right String This is used to extract characters from the end of a string.

Batch Script - Arrays

Each element of the array needs to be defined with the set command. The 'for' loop would be required to iterate through the values of the array.

 Creating an Array

An array is created by using the following set command. set a[0]=1 Where 0 is the index of the array and 1 is the value assigned to the first element of the array. Another way to implement arrays is to define a list of values and iterate through the list of values. The following example show how this can be implemented.

Example

@echo off set list=1 2 3 4 (for %%a in (%list%) do ( echo %%a ))

Output

The above command produces the following output. 1 2 3 4

 Accessing Arrays

You can retrieve a value from the array by using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array.

Example

@echo off set a[0]=1 echo %a[0]% In this example, the index starts from 0 which means the first element can be accessed using index as 0, the second element can be accessed using index as 1 and so on. Let's check the following example to create, initialize and access arrays - @echo off set a[0]=1 set a[1]=2 set a[2]=3 echo The first element of the array is %a[0]% echo The second element of the array is %a[1]% echo The third element of the array is %a[2]% The above command produces the following output. The first element of the array is 1 The second element of the array is 2 The third element of the array is 3

 Modifying an Array

To add an element to the end of the array, you can use the set element along with the last index of the array element.

Example

@echo off set a[0]=1 set a[1]=2 set a[2]=3 Rem Adding an element at the end of an array Set a[3]=4 echo The last element of the array is %a[3]% The above command produces the following output. The last element of the array is 4 You can modify an existing element of an Array by assigning a new value at a given index as shown in the following example - @echo off set a[0]=1 set a[1]=2 set a[2]=3 Rem Setting the new value for the second element of the array Set a[1]=5 echo The new value of the second element of the array is %a[1]% The above command produces the following output. The new value of the second element of the array is 5

 Iterating Over an Array

Iterating over an array is achieved by using the 'for' loop and going through each element of the array. The following example shows a simple way that an array can be implemented. @echo off setlocal enabledelayedexpansion set topic[0]=comments set topic[1]=variables set topic[2]=Arrays set topic[3]=Decision making set topic[4]=Time and date set topic[5]=Operators for /l %%n in (0,1,5) do ( echo !topic[%%n]! ) Following things need to be noted about the above program - Each element of the array needs to be specifically defined using the set command. The 'for' loop with the /L parameter for moving through ranges is used to iterate through the array.

Output

The above command produces the following output. Comments variables Arrays Decision making Time and date Operators

 Length of an Array

The length of an array is done by iterating over the list of values in the array since there is no direct function to determine the number of elements in an array. @echo off set Arr[0]=1 set Arr[1]=2 set Arr[2]=3 set Arr[3]=4 set "x = 0" :SymLoop if defined Arr[%x%] ( call echo %%Arr[%x%]%% set /a "x+=1" GOTO :SymLoop ) echo "The length of the array is" %x%

Output

Output The above command produces the following output. 1 2 3 4 "The length of the array is" 4

 Creating Structures in Arrays

Structures can also be implemented in batch files using a little bit of an extra coding for implementation. The following example shows how this can be achieved.

Example

@echo off set obj[0].Name=Joe set obj[0].ID=1 set obj[1].Name=Mark set obj[1].ID=2 set obj[2].Name=Mohan set obj[2].ID=3 FOR /L %%i IN (0 1 2) DO ( call echo Name = %%obj[%%i].Name%% call echo Value = %%obj[%%i].ID%% ) The following key things need to be noted about the above code. Each variable defined using the set command has 2 values associated with each index of the array. The variable i is set to 0 so that we can loop through the structure will the length of the array which is 3. We always check for the condition on whether the value of i is equal to the value of len and if not, we loop through the code. We are able to access each element of the structure using the obj[%i%] notation.

Output

The above command produces the following output. Name=Joe Value=1 Name=Mark Value=2 Name=Mohan Value=3

Batch Script - Decision Making

S.NoStrings & Description
1If Statement The first decision-making statement is the 'if' statement.
2If/else Statement The next decision making statement is the If/else statement. Following is the general form of this statement.
3Nested If Statements Sometimes, there is a requirement to have multiple 'if' statement embedded inside each other. Following is the general form of this statement.

Batch Script - Operators

In batch script, the following types of operators are possible. Arithmetic operators Relational operators Logical operators Assignment operators Bitwise operators

 Arithmetic Operators

Batch script language supports the normal Arithmetic operators as any language. Following are the Arithmetic operators available. Show Example
OperatorDescriptionExample
+Addition of two operands1 + 2 will give 3
-Subtracts second operand from the first2 - 1 will give 1
*Multiplication of both operands2 * 2 will give 4
/Division of the numerator by the denominator3 / 2 will give 1.5
%Modulus operator and remainder of after an integer/float division3 % 2 will give 1

 Relational Operators

Relational operators allow of the comparison of objects. Below are the relational operators available. Show Example
OperatorDescriptionExample
EQUTests the equality between two objects2 EQU 2 will give true
NEQTests the difference between two objects3 NEQ 2 will give true
LSSChecks to see if the left object is less than the right operand2 LSS 3 will give true
LEQChecks to see if the left object is less than or equal to the right operand2 LEQ 3 will give true
GTRChecks to see if the left object is greater than the right operand3 GTR 2 will give true
GEQChecks to see if the left object is greater than or equal to the right operand3 GEQ 2 will give true

 Logical Operators

Logical operators are used to evaluate Boolean expressions. Following are the logical operators available. The batch language is equipped with a full set of Boolean logic operators like AND, OR, XOR, but only for binary numbers. Neither are there any values for TRUE or FALSE. The only logical operator available for conditions is the NOT operator. Show Example
OperatorDescription
ANDThis is the logical ※and§ operator
ORThis is the logical ※or§ operator
NOTThis is the logical ※not§ operator

 Assignment Operators

Batch Script language also provides assignment operators. Following are the assignment operators available. Show Example
OperatorDescriptionExample
+=This adds right operand to the left operand and assigns the result to left operandSet /A a = 5 a += 3 Output will be 8
-=This subtracts the right operand from the left operand and assigns the result to the left operandSet /A a = 5 a -= 3 Output will be 2
*=This multiplies the right operand with the left operand and assigns the result to the left operandSet /A a = 5 a *= 3 Output will be 15
/=This divides the left operand with the right operand and assigns the result to the left operandSet /A a = 6 a/ = 3 Output will be 2
%=This takes modulus using two operands and assigns the result to the left operandSet /A a = 5 a% = 3 Output will be 2

 Bitwise Operators

Bitwise operators are also possible in batch script. Following are the operators available. Show Example
OperatorDescription
&This is the bitwise ※and§ operator
|This is the bitwise ※or§ operator
^This is the bitwise ※xor§ or Exclusive or operator
Following is the truth table showcasing these operators.
pqp & qp | qp ^ q
00000
01011
11110
10011

Batch Script - DATE and TIME

 DATE

This command gets the system date.

Syntax

DATE

Example

@echo off echo %DATE%

Output

The current date will be displayed in the command prompt. For example, Mon 12/28/2015

 TIME

This command sets or displays the time.

Syntax

TIME

Example

@echo off echo %TIME%

Output

The current system time will be displayed. For example, 22:06:52.87 Following are some implementations which can be used to get the date and time in different formats.

 Date in Format Year-Month-Day

Example

@echo off echo/Today is: %year%-%month%-%day% goto :EOF setlocal ENABLEEXTENSIONS set t = 2&if "%date%z" LSS "A" set t = 1 for /f "skip=1 tokens = 2-4 delims = (-)" %%a in ('echo/^|date') do ( for /f "tokens = %t%-4 delims=.-/ " %%d in ('date/t') do ( set %%a=%%d&set %%b=%%e&set %%c=%%f)) endlocal&set %1=%yy%&set %2=%mm%&set %3=%dd%&goto :EOF

Output

The above command produces the following output. Today is: 2015-12-30

Batch Script - Input / Output

Each of these three standard files, otherwise known as the standard streams, are referenced using the numbers 0, 1, and 2. Stdin is file 0, stdout is file 1, and stderr is file 2.

 Redirecting Output (Stdout and Stderr)

One common practice in batch files is sending the output of a program to a log file. The > operator sends, or redirects, stdout or stderr to another file. The following example shows how this can be done. Dir C:\ > list.txt In the above example, the stdout of the command Dir C:\ is redirected to the file list.txt. If you append the number 2 to the redirection filter, then it would redirect the stderr to the file lists.txt. Dir C:\ 2> list.txt One can even combine the stdout and stderr streams using the file number and the '&' prefix. Following is an example. DIR C:\ > lists.txt 2>&1

 Suppressing Program Output

The pseudo file NUL is used to discard any output from a program. The following example shows that the output of the command DIR is discarded by sending the output to NUL. Dir C:\ > NUL

Stdin

To work with the Stdin, you have to use a workaround to achieve this. This can be done by redirecting the command prompt's own stdin, called CON. The following example shows how you can redirect the output to a file called lists.txt. After you execute the below command, the command prompt will take all the input entered by user till it gets an EOF character. Later, it sends all the input to the file lists.txt. TYPE CON > lists.txt

Batch Script - Return Code

Following are the common exit code and their description.
Error CodeDescription
0Program successfully completed.
1Incorrect function. Indicates that Action has attempted to execute non-recognized command in Windows command prompt cmd.exe.
2The system cannot find the file specified. Indicates that the file cannot be found in specified location.
3The system cannot find the path specified. Indicates that the specified path cannot be found.
5Access is denied. Indicates that user has no access right to specified resource.

9009

0x2331

Program is not recognized as an internal or external command, operable program or batch file. Indicates that command, application name or path has been misspelled when configuring the Action.

221225495

0xC0000017

-1073741801

Not enough virtual memory is available. It indicates that Windows has run out of memory.

3221225786

0xC000013A

-1073741510

The application terminated as a result of a CTRL+C. Indicates that the application has been terminated either by the user's keyboard input CTRL+C or CTRL+Break or closing command prompt window.

3221225794

0xC0000142

-1073741502

The application failed to initialize properly. Indicates that the application has been launched on a Desktop to which the current user has no access rights. Another possible cause is that either gdi32.dll or user32.dll has failed to initialize.

 Error Level

The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script. By default, the way to check for the ERRORLEVEL is via the following code.

Syntax

IF %ERRORLEVEL% NEQ 0 ( DO_Something ) It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file. EXIT /B at the end of the batch file will stop execution of a batch file. Use EXIT /B < exitcodes > at the end of the batch file to return custom return codes. Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file, which is the latest error codes from the last command executed. In the batch file, it is always a good practice to use environment variables instead of constant values, since the same variable get expanded to different values on different computers. Let's look at a quick example on how to check for error codes from a batch file.

Example

Let's assume we have a batch file called Find.cmd which has the following code. In the code, we have clearly mentioned that we if don't find the file called lists.txt then we should set the errorlevel to 7. Similarly, if we see that the variable userprofile is not defined then we should set the errorlevel code to 9. if not exist c:\lists.txt exit 7 if not defined userprofile exit 9 exit 0 Let's assume we have another file called App.cmd that calls Find.cmd first. Now, if the Find.cmd returns an error wherein it sets the errorlevel to greater than 0 then it would exit the program. In the following batch file, after calling the Find.cnd find, it actually checks to see if the errorlevel is greater than 0. Call Find.cmd if errorlevel gtr 0 exit echo ※Successful completion§

Output

In the above program, we can have the following scenarios as the output - If the file c:\lists.txt does not exist, then nothing will be displayed in the console output. If the variable userprofile does not exist, then nothing will be displayed in the console output. If both of the above condition passes then the string ※Successful completion§ will be displayed in the command prompt.

 Loops

In the decision making chapter, we have seen statements which have been executed one after the other in a sequential manner. Additionally, implementations can also be done in Batch Script to alter the flow of control in a program's logic. They are then classified into flow of control statements.
S.NoLoops & Description
1While Statement Implementation There is no direct while statement available in Batch Script but we can do an implementation of this loop very easily by using the if statement and labels.
2For Statement - List Implementations The "FOR" construct offers looping capabilities for batch files. Following is the common construct of the 'for' statement for working with a list of values.
3Looping through Ranges The 'for' statement also has the ability to move through a range of values. Following is the general form of the statement.
4Classic for Loop Implementation Following is the classic 'for' statement which is available in most programming languages.

 Looping through Command Line Arguments

The 'for' statement can also be used for checking command line arguments. The following example shows how the 'for' statement can be used to loop through the command line arguments.

Example

@ECHO OFF :Loop IF "%1"=="" GOTO completed FOR %%F IN (%1) DO echo %%F SHIFT GOTO Loop :completed

Output

Let's assume that our above code is stored in a file called Test.bat. The above command will produce the following output if the batch file passes the command line arguments of 1,2 and 3 as Test.bat 1 2 3. 1 2 3
S.NoLoops & Description
1Break Statement Implementation The break statement is used to alter the flow of control inside loops within any programming language. The break statement is normally used in looping constructs and is used to cause immediate termination of the innermost enclosing loop.

Batch Script - Functions

As like any other languages, functions in Batch Script follows the same procedure - Function Declaration - It tells the compiler about a function's name, return type, and parameters. Function Definition - It provides the actual body of the function. In Batch Script, a function is defined by using the label statement. When a function is newly defined, it may take one or several values as input 'parameters' to the function, process the functions in the main body, and pass back the values to the functions as output 'return types'. Every function has a function name, which describes the task that the function performs. To use a function, you "call" that function with its name and pass its input values (known as arguments) that matches the types of the function's parameters. Following is the syntax of a simple function. :function_name Do_something EXIT /B 0 The function_name is the name given to the function which should have some meaning to match what the function actually does. The EXIT statement is used to ensure that the function exits properly. Following is an example of a simple function.

Example

:Display SET /A index=2 echo The value of index is %index% EXIT /B 0
S.NoFunctions & Description
1Calling a Function A function is called in Batch Script by using the call command.
2Functions with Parameters Functions can work with parameters by simply passing them when a call is made to the function.
3Functions with Return Values Functions can work with return values by simply passing variables names
4Local Variables in Functions Local variables in functions can be used to avoid name conflicts and keep variable changes local to the function.
5Recursive Functions The ability to completely encapsulate the body of a function by keeping variable changes local to the function and invisible to the caller.
6File I/O In Batch Script, it is possible to perform the normal file I/O operations that would be expected in any programming language.
7Creating Files The creation of a new file is done with the help of the redirection filter >. This filter can be used to redirect any output to a file.
8Writing to Files Content writing to files is also done with the help of the redirection filter >. This filter can be used to redirect any output to a file.
9Appending to Files Content writing to files is also done with the help of the double redirection filter >>. This filter can be used to append any output to a file.
10Reading from Files Reading of files in a batch script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read.
11Deleting Files For deleting files, Batch Script provides the DEL command.
12Renaming Files For renaming files, Batch Script provides the REN or RENAME command.
13Moving Files For moving files, Batch Script provides the MOVE command.
14Batch Files Pipes The pipe operator (|) takes the output (by default, STDOUT) of one command and directs it into the input (by default, STDIN) of another command.
15Batch Files Inputs When a batch file is run, it gives you the option to pass in command line parameters which can then be read within the program for further processing.
16Using the SHIFT Operator One of the limitations of command line arguments is that it can accept only arguments till %9. Let's take an example of this limitation.
17Folders In Batch Script, it is possible to perform the normal folder based operations that would be expected in any programming language.
18Creating Folders The creation of a folder is done with the assistance of the MD (Make directory) command.
19Listing Folder Contents The listing of folder contents can be done with the dir command. This command allows you to see the available files and directories in the current directory.
20Deleting Folders For deleting folders, Batch Scripting provides the DEL command.
21Renaming Folders For renaming folders, Batch Script provides the REN or RENAME command.
22Moving Folders For moving folders, Batch Script provides the MOVE command.

Batch Script - Process

 Viewing the List of Running Processes

In Batch Script, the TASKLIST command can be used to get the list of currently running processes within a system.

Syntax

TASKLIST [/S system [/U username [/P [password]]]] [/M [module] | /SVC | /V] [/FI filter] [/FO format] [/NH]